@activeagents/browser-sidecar 1.9.2 → 1.9.3

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -68,10 +68,13 @@ other version.
68
68
  | `DELETE /mcp` | ends the session in `Mcp-Session-Id` |
69
69
  | `GET /live` | the live view's WebSocket, when `live` is configured |
70
70
  | `GET /storage-state` | `{ "storage_state": { "cookies": […], "origins": […] } }`: the browser's cookies and localStorage for the app, so a sign-in made in it can be kept |
71
+ | `POST /tokens` | `{ "label": "…" }` in, `{ "id", "token", "label", "expires_at" }` out: a client token for `/mcp` |
72
+ | `DELETE /tokens/:id` | revokes one |
71
73
 
72
74
  Every request, a WebSocket upgrade other than the live view's included, must:
73
75
 
74
- - carry `Authorization: Bearer <token>`;
76
+ - carry `Authorization: Bearer <token>`, or, for `/mcp` only, a live client
77
+ token;
75
78
  - name an accepted `Host`: the listening address and port, the loopback names
76
79
  when listening on loopback or on every interface, and `allowed_hosts`;
77
80
  - carry no `Origin` header. A page in a browser always sends one, so a page
@@ -80,6 +83,27 @@ Every request, a WebSocket upgrade other than the live view's included, must:
80
83
 
81
84
  No CORS header is ever sent.
82
85
 
86
+ ### Client tokens
87
+
88
+ A client that runs other people's code, such as Claude Code, whose shell
89
+ commands inherit its environment, should never hold the master token. The
90
+ dashboard mints it a client token for one turn (`POST /tokens`, with the
91
+ master token) and revokes it when the turn ends. A client token reaches
92
+ `/mcp` only, expires after six hours unless revoked first, and at most 32 are
93
+ live at once. Its `label` names the client wherever the live view shows it,
94
+ such as "Claude Code · turn 3 is waiting for control".
95
+
96
+ ### Handoffs between an agent and a person
97
+
98
+ - When people took or handed back control since an MCP session's last tool
99
+ call, its next result starts with a note saying who and when, and that the
100
+ page may have changed, so the agent takes a snapshot before acting.
101
+ - With the live view on, the `browser_request_person` tool is offered: an
102
+ agent asks the person watching to take over, with a reason. The sidecar
103
+ answers it at once, and every viewer is sent
104
+ `{ "type": "person_requested", "request": { reason, client, at } }`, also
105
+ in `ready`, until someone takes control.
106
+
83
107
  ## The live view
84
108
 
85
109
  The dashboard's page opens `ws://<host>:<port>/live` itself, so the upgrade
@@ -138,6 +162,47 @@ back are recorded as `marker` events (`takeover_started`, `takeover_ended`,
138
162
  with `source: "human"` and who), and what the person changed shows in the
139
163
  masked rrweb stream.
140
164
 
165
+ ### Uploading files
166
+
167
+ A page's `<input type="file">` opens a file chooser, which a headless browser
168
+ has no dialog for. When one opens while a person holds control, every viewer
169
+ is sent `{ type: "file_chooser", chooser: { id, multiple, accept, since,
170
+ max_files, max_file_bytes } }` (and `ready` carries it as `file_chooser` for
171
+ a viewer who joins), and only the person driving may answer it:
172
+
173
+ ```json
174
+ { "type": "file_upload", "chooser": "<id>", "files": [{ "name": "notes.txt", "size": 11 }] }
175
+ { "type": "file_chunk", "chooser": "<id>", "data": "<base64, at most 32 KiB before encoding>" }
176
+ { "type": "file_cancel", "chooser": "<id>" }
177
+ ```
178
+
179
+ The chunks carry the files' bytes in the order they were listed, one file
180
+ running on into the next. Once the last byte arrives the files are set on the
181
+ input and the uploader is sent `{ type: "file_upload", chooser, status:
182
+ "done" }`; on the way, `"progress"` with `received` and `total` about every
183
+ MiB; and on a refusal, `"failed"` with a `code`: `not_driving`, `no_chooser`,
184
+ `too_many`, `too_large`, `bad_upload` or `upload_failed`. Everyone is then
185
+ sent `file_chooser` with `chooser: null`, as they are when the person cancels,
186
+ hands back control or lets five minutes pass without sending anything.
187
+
188
+ Each file is written, mode 0600, to a directory of its own under the
189
+ working directory, named by its last path segment without control or
190
+ reserved characters, and stays there until the browser stops, as the page
191
+ reads it from disk. `live.upload_max_file_bytes`, `live.upload_max_files`
192
+ (`0` turns uploads off) and `live.upload_max_session_bytes` bound it. File
193
+ names and contents are never logged or recorded; an upload is recorded as a
194
+ `file_uploaded` marker with its file count and size.
195
+
196
+ The sidecar listens for choosers only while someone holds control, as
197
+ Playwright intercepts them while anything listens: the rest of the time a
198
+ headed browser's own dialog opens, and an agent's chooser is left to
199
+ Playwright MCP's `browser_file_upload`. When someone takes control while an
200
+ agent's chooser waits there, it is offered to them. When the person answers a
201
+ chooser, or cancels one that opened while they drove, the modal state
202
+ Playwright MCP keeps for it is cleared too, so the agent's next call is not
203
+ refused for it. An agent's chooser the person leaves unanswered stays the
204
+ agent's.
205
+
141
206
  ## The command
142
207
 
143
208
  ```
@@ -181,7 +246,10 @@ browser, posts what it has recorded, and removes its directories.
181
246
  "session_id": "…",
182
247
  "origins": ["http://localhost:3000"],
183
248
  "agent_wait_ms": 20000,
184
- "release_grace_ms": 10000
249
+ "release_grace_ms": 10000,
250
+ "upload_max_file_bytes": 26214400,
251
+ "upload_max_files": 10,
252
+ "upload_max_session_bytes": 262144000
185
253
  },
186
254
  "storage_state": { "cookies": [], "origins": [] }
187
255
  }
@@ -199,7 +267,7 @@ browser, posts what it has recorded, and removes its directories.
199
267
  | `stop_at` | when to stop on its own, as epoch milliseconds or ISO 8601 |
200
268
  | `chromium_sandbox` | `false` where Chromium's own sandbox cannot run, as in a container without the privileges it needs |
201
269
  | `recording` | where to post recorded events, and the batch limits the ingest enforces; nothing is recorded when unset |
202
- | `live` | the live view: the sandbox session tickets must name, the dashboard origins that may open it, how long an agent's call waits for control (at most 45000 ms) and how long control outlives a dropped connection; no live view when unset |
270
+ | `live` | the live view: the sandbox session tickets must name, the dashboard origins that may open it, how long an agent's call waits for control (at most 45000 ms), how long control outlives a dropped connection, and how much a person may upload (25 MiB a file, 10 files a chooser and 250 MiB in all by default; see [Uploading files](#uploading-files)); no live view when unset |
203
271
  | `storage_state` | a Playwright storage state the browser starts with, such as a sign-in saved from `GET /storage-state`; only the cookies sent to the app's host and the localStorage of its origin are applied |
204
272
 
205
273
  ## The image
@@ -0,0 +1,97 @@
1
+ import { createHash, randomBytes, randomUUID, timingSafeEqual } from 'node:crypto';
2
+
3
+ // How many client tokens may be live at once, and the longest a label may be.
4
+ export const MAX_CLIENT_TOKENS = 32;
5
+ export const MAX_LABEL_LENGTH = 120;
6
+ // How long a client token lasts unless revoked first.
7
+ export const DEFAULT_CLIENT_TOKEN_TTL_MS = 6 * 60 * 60_000;
8
+
9
+ function digest(value) {
10
+ return createHash('sha256').update(value).digest();
11
+ }
12
+
13
+ function cleanLabel(label) {
14
+ if (typeof label !== 'string') return null;
15
+ const clean = label.replace(/[\u0000-\u001f\u007f]/g, '').trim().slice(0, MAX_LABEL_LENGTH);
16
+ return clean === '' ? null : clean;
17
+ }
18
+
19
+ /**
20
+ * Used to hand out scoped, revocable tokens for the MCP endpoint, so a client
21
+ * that runs other people's code (Claude Code, whose shell commands inherit
22
+ * its environment) never holds the master token, and loses access the
23
+ * moment its turn ends.
24
+ *
25
+ * A client token may only call /mcp. Minting and revoking one, and every
26
+ * other endpoint, take the master token (see http-server).
27
+ *
28
+ * Each token carries a label ("Claude Code · turn 42"), which the gateway
29
+ * tags that client's tool calls with: the live view names who is waiting
30
+ * for control by it.
31
+ */
32
+ export class ClientTokens {
33
+ /**
34
+ * @param {object} [options]
35
+ * @param {number} [options.max]
36
+ * @param {number} [options.ttlMs]
37
+ * @param {() => number} [options.now]
38
+ */
39
+ constructor({ max = MAX_CLIENT_TOKENS, ttlMs = DEFAULT_CLIENT_TOKEN_TTL_MS, now = Date.now } = {}) {
40
+ this.max = max;
41
+ this.ttlMs = ttlMs;
42
+ this.now = now;
43
+ this.tokens = new Map();
44
+ }
45
+
46
+ /**
47
+ * Mints a token.
48
+ *
49
+ * @param {{ label?: string }} [request]
50
+ * @returns {{ id: string, token: string, label: string|null, expires_at: string }}
51
+ * @throws {Error} with status 429 when too many are live
52
+ */
53
+ mint({ label } = {}) {
54
+ this.prune();
55
+ if (this.tokens.size >= this.max) throw Object.assign(new Error('Too many client tokens are live'), { status: 429 });
56
+
57
+ const id = randomUUID();
58
+ const token = `cl_${randomBytes(32).toString('base64url')}`;
59
+ const entry = { id, digest: digest(token), label: cleanLabel(label), expiresAt: this.now() + this.ttlMs };
60
+ this.tokens.set(id, entry);
61
+ return { id, token, label: entry.label, expires_at: new Date(entry.expiresAt).toISOString() };
62
+ }
63
+
64
+ /**
65
+ * @param {string} id
66
+ * @returns {boolean} whether there was such a token
67
+ */
68
+ revoke(id) {
69
+ return this.tokens.delete(id);
70
+ }
71
+
72
+ /**
73
+ * The live client `token` matches, or null.
74
+ *
75
+ * @param {string} token
76
+ * @returns {{ id: string, label: string|null } | null}
77
+ */
78
+ match(token) {
79
+ if (typeof token !== 'string' || !token.startsWith('cl_')) return null;
80
+ this.prune();
81
+ const presented = digest(token);
82
+ for (const entry of this.tokens.values()) {
83
+ if (timingSafeEqual(presented, entry.digest)) return { id: entry.id, label: entry.label };
84
+ }
85
+ return null;
86
+ }
87
+
88
+ prune() {
89
+ const now = this.now();
90
+ for (const [id, entry] of this.tokens) if (entry.expiresAt <= now) this.tokens.delete(id);
91
+ }
92
+
93
+ get size() {
94
+ this.prune();
95
+ return this.tokens.size;
96
+ }
97
+ }
package/lib/config.mjs CHANGED
@@ -13,10 +13,13 @@
13
13
  // "chromium_sandbox": true, false where Chromium's own sandbox cannot run (some containers)
14
14
  // "recording": { "url": "...", "token": "...", "batch_events": 1000, "batch_bytes": 1048576 },
15
15
  // "live": { "session_id": "...", "origins": ["http://localhost:3000"],
16
- // "agent_wait_ms": 20000, "release_grace_ms": 10000 }
16
+ // "agent_wait_ms": 20000, "release_grace_ms": 10000,
17
+ // "upload_max_file_bytes": 26214400, "upload_max_files": 10,
18
+ // "upload_max_session_bytes": 262144000 }
17
19
  // "storage_state": { "cookies": [...], "origins": [...] } a saved sign-in the browser starts with
18
20
  // }
19
21
 
22
+ import { DEFAULT_UPLOAD_LIMITS } from './file-upload.mjs';
20
23
  import { appStorageState, StorageStateError } from './storage-state.mjs';
21
24
 
22
25
  export const MODES = ['headless', 'headed'];
@@ -33,6 +36,9 @@ const DEFAULT_BATCH_BYTES = 1024 * 1024;
33
36
  const DEFAULT_AGENT_WAIT_MS = 20_000;
34
37
  export const MAX_AGENT_WAIT_MS = 45_000;
35
38
  const DEFAULT_RELEASE_GRACE_MS = 10_000;
39
+ // The most a live view upload may be configured to take, per file and in all.
40
+ export const MAX_UPLOAD_FILES = 100;
41
+ export const MAX_UPLOAD_SESSION_BYTES = 2 * 1024 * 1024 * 1024;
36
42
 
37
43
  export class ConfigError extends Error {}
38
44
 
@@ -106,6 +112,20 @@ function origin(value) {
106
112
  return url.origin;
107
113
  }
108
114
 
115
+ // How much a person may upload through the live view. upload_max_files 0
116
+ // turns uploads off.
117
+ function uploadLimits(value) {
118
+ const maxSessionBytes = nonNegativeInteger(value.upload_max_session_bytes, 'live.upload_max_session_bytes',
119
+ DEFAULT_UPLOAD_LIMITS.maxSessionBytes, MAX_UPLOAD_SESSION_BYTES);
120
+ const maxFileBytes = nonNegativeInteger(value.upload_max_file_bytes, 'live.upload_max_file_bytes',
121
+ Math.min(DEFAULT_UPLOAD_LIMITS.maxFileBytes, maxSessionBytes), maxSessionBytes);
122
+ return {
123
+ maxFileBytes,
124
+ maxFiles: nonNegativeInteger(value.upload_max_files, 'live.upload_max_files', DEFAULT_UPLOAD_LIMITS.maxFiles, MAX_UPLOAD_FILES),
125
+ maxSessionBytes,
126
+ };
127
+ }
128
+
109
129
  function live(value) {
110
130
  if (value === undefined || value === null) return null;
111
131
  if (typeof value !== 'object' || Array.isArray(value)) fail('live must be an object');
@@ -119,6 +139,7 @@ function live(value) {
119
139
  origins: [...new Set(value.origins.map(origin))],
120
140
  agentWaitMs: nonNegativeInteger(value.agent_wait_ms, 'live.agent_wait_ms', DEFAULT_AGENT_WAIT_MS, MAX_AGENT_WAIT_MS),
121
141
  releaseGraceMs: positiveInteger(value.release_grace_ms, 'live.release_grace_ms', DEFAULT_RELEASE_GRACE_MS),
142
+ uploadLimits: uploadLimits(value),
122
143
  };
123
144
  }
124
145
 
@@ -45,6 +45,9 @@ export function sameUser(a, b) {
45
45
  return a.id !== null && a.id === b.id;
46
46
  }
47
47
 
48
+ // How many control changes the journal keeps.
49
+ export const JOURNAL_LIMIT = 50;
50
+
48
51
  /**
49
52
  * Used to let one person at a time drive the browser by hand. While someone
50
53
  * holds control, an agent's call that changes the page waits for them to
@@ -54,11 +57,15 @@ export function sameUser(a, b) {
54
57
  * `{ key, user: { id, name }, since }`. A user with an id may move control
55
58
  * between their own connections: a second tab, or a reconnect.
56
59
  *
60
+ * Every change of holder is also kept in a short journal (#journal,
61
+ * #changesSince), so an agent can be told that a person drove the browser
62
+ * since its last call: the page may not be what it last saw.
63
+ *
57
64
  * Events:
58
65
  * change (holder, previous, reason) whenever the holder changes;
59
66
  * reason is "taken", "moved", "handed_back", "disconnected"
60
67
  * or "closed"
61
- * agent_waiting ({ tool, since }) an agent's call began to wait
68
+ * agent_waiting ({ tool, since, client }) an agent's call began to wait
62
69
  * agent_done ({ tool, admitted }) it stopped waiting, run or refused
63
70
  */
64
71
  export class ControlLock extends EventEmitter {
@@ -75,6 +82,29 @@ export class ControlLock extends EventEmitter {
75
82
  this.graceTimer = null;
76
83
  this.waiting = new Set();
77
84
  this.closed = false;
85
+ this.journal = [];
86
+ this.journalSeq = 0;
87
+ this.on('change', (holder, previous, reason) => this.record(holder, previous, reason));
88
+ }
89
+
90
+ // Notes a change of holder in the journal. Control moving between one
91
+ // user's connections changes nothing an agent would need to hear of.
92
+ record(holder, previous, reason) {
93
+ if (holder && previous) return;
94
+ const user = (holder ?? previous)?.user ?? { id: null, name: null };
95
+ this.journalSeq += 1;
96
+ this.journal.push({ seq: this.journalSeq, at: this.now(), type: holder ? 'taken' : 'released', reason, user: user.name ?? null });
97
+ if (this.journal.length > JOURNAL_LIMIT) this.journal.splice(0, this.journal.length - JOURNAL_LIMIT);
98
+ }
99
+
100
+ /**
101
+ * The control changes after `seq`, oldest first.
102
+ *
103
+ * @param {number} seq
104
+ * @returns {Array<{ seq: number, at: number, type: 'taken'|'released', reason: string, user: string|null }>}
105
+ */
106
+ changesSince(seq) {
107
+ return this.journal.filter((entry) => entry.seq > seq);
78
108
  }
79
109
 
80
110
  /**
@@ -137,13 +167,14 @@ export class ControlLock extends EventEmitter {
137
167
  * @param {string} name the tool
138
168
  * @param {object} args its arguments
139
169
  * @param {number} waitMs
170
+ * @param {string|null} [client] who is calling, as the live view names them ("Claude Code · turn 3")
140
171
  * @returns {Promise<{ holder: object }|{ stopping: true }|null>} null to run the call; otherwise why it
141
172
  * is refused: the holder who kept control past `waitMs`, or `stopping` when the lock closed meanwhile
142
173
  */
143
- async admit(name, args, waitMs) {
174
+ async admit(name, args, waitMs, client = null) {
144
175
  if (!this.holder || !changesPage(name, args)) return null;
145
176
 
146
- const wait = { tool: name, since: this.now() };
177
+ const wait = { tool: name, since: this.now(), client };
147
178
  const deadline = wait.since + waitMs;
148
179
  this.waiting.add(wait);
149
180
  this.emit('agent_waiting', wait);
@@ -0,0 +1,412 @@
1
+ import { randomUUID } from 'node:crypto';
2
+ import { EventEmitter } from 'node:events';
3
+ import { mkdir, open, rm } from 'node:fs/promises';
4
+ import { join } from 'node:path';
5
+
6
+ // The bytes a viewer sends in one file_chunk message, before base64. Encoded,
7
+ // a chunk and its envelope stay well under the live view's 64 KiB message cap.
8
+ export const UPLOAD_CHUNK_BYTES = 32 * 1024;
9
+ const MAX_CHUNK_CHARS = Math.ceil(UPLOAD_CHUNK_BYTES / 3) * 4;
10
+ const BASE64 = /^[A-Za-z0-9+/]*={0,2}$/;
11
+ const MAX_NAME_BYTES = 200;
12
+ // How often, in bytes received, the uploader is told how far it has got.
13
+ const PROGRESS_EVERY_BYTES = 1024 * 1024;
14
+
15
+ export const DEFAULT_UPLOAD_LIMITS = Object.freeze({
16
+ maxFileBytes: 25 * 1024 * 1024,
17
+ maxFiles: 10,
18
+ maxSessionBytes: 250 * 1024 * 1024,
19
+ });
20
+ // How long a file chooser waits for the person driving to answer it, counted
21
+ // again from each chunk they send.
22
+ const CHOOSER_TIMEOUT_MS = 5 * 60 * 1000;
23
+
24
+ /** Raised for an upload the sidecar refuses; `code` names why. */
25
+ export class UploadError extends Error {
26
+ constructor(code, message) {
27
+ super(message);
28
+ this.code = code;
29
+ }
30
+ }
31
+
32
+ /**
33
+ * Returns the name a file a viewer sent is saved and shown to the page
34
+ * under: its last path segment, without control characters, characters
35
+ * file systems refuse, or leading dots, and at most MAX_NAME_BYTES of UTF-8.
36
+ * "upload" when nothing is left.
37
+ *
38
+ * @param {unknown} name
39
+ * @returns {string}
40
+ */
41
+ export function sanitizeFileName(name) {
42
+ if (typeof name !== 'string') return 'upload';
43
+
44
+ let clean = name.split(/[\\/]/).at(-1)
45
+ .replace(/[\u0000-\u001f\u007f<>:"|?*]/g, '')
46
+ .replace(/^[.\s]+/, '')
47
+ .trim();
48
+ while (Buffer.byteLength(clean, 'utf8') > MAX_NAME_BYTES) clean = [...clean].slice(0, -1).join('');
49
+ return clean === '' ? 'upload' : clean;
50
+ }
51
+
52
+ /**
53
+ * Clears the file chooser modal state Playwright MCP keeps on its tab for
54
+ * `chooser`, so an agent's next tool call is not refused for a chooser the
55
+ * person driving already answered or cancelled. Playwright MCP keeps its tab
56
+ * on the page under a private symbol, so this looks for any symbol whose
57
+ * value has its modal state methods; a version without them is left alone.
58
+ *
59
+ * @param {import('playwright').Page} page
60
+ * @param {import('playwright').FileChooser} chooser
61
+ */
62
+ export function clearAgentFileChooser(page, chooser) {
63
+ for (const symbol of Object.getOwnPropertySymbols(page)) {
64
+ const tab = page[symbol];
65
+ if (typeof tab?.modalStates !== 'function' || typeof tab.clearModalState !== 'function') continue;
66
+ for (const state of tab.modalStates()) {
67
+ if (state?.type === 'fileChooser' && state.fileChooser === chooser) tab.clearModalState(state);
68
+ }
69
+ }
70
+ }
71
+
72
+ /**
73
+ * The file choosers Playwright MCP holds open on `page` for an agent, as
74
+ * modal states of its tab (see clearAgentFileChooser): a page that asked an
75
+ * agent for files while nobody held control.
76
+ *
77
+ * @param {import('playwright').Page} page
78
+ * @returns {import('playwright').FileChooser[]}
79
+ */
80
+ export function agentFileChoosers(page) {
81
+ const choosers = [];
82
+ for (const symbol of Object.getOwnPropertySymbols(page)) {
83
+ const tab = page[symbol];
84
+ if (typeof tab?.modalStates !== 'function') continue;
85
+ for (const state of tab.modalStates()) {
86
+ if (state?.type === 'fileChooser' && state.fileChooser) choosers.push(state.fileChooser);
87
+ }
88
+ }
89
+ return choosers;
90
+ }
91
+
92
+ function decodeChunk(data) {
93
+ if (typeof data !== 'string' || data === '' || data.length > MAX_CHUNK_CHARS || data.length % 4 !== 0 || !BASE64.test(data)) {
94
+ throw new UploadError('bad_upload', 'A file chunk must be base64, at most 32 KiB before encoding');
95
+ }
96
+ return Buffer.from(data, 'base64');
97
+ }
98
+
99
+ /**
100
+ * Used to hand a file to a page's <input type="file"> from the live view.
101
+ *
102
+ * While someone holds control (ControlLock), a page that opens a file
103
+ * chooser is offered to the live view instead (#state): headless Chromium
104
+ * has no dialog to show, and a headed one's is on the sandbox's screen, not
105
+ * the viewer's. Only the person holding control may answer it, by sending
106
+ * the files' bytes (#begin, #chunk), which are written to a directory of
107
+ * their own, readable only by this process, and set on the input. They stay
108
+ * there until the browser stops, as the page's File objects read them from
109
+ * disk, and count against maxSessionBytes until then.
110
+ *
111
+ * A chooser an agent opened while nobody held control, and left waiting on
112
+ * Playwright MCP's browser_file_upload, is offered too once someone takes
113
+ * control (#adoptAgentChooser); answering it clears the agent's wait.
114
+ *
115
+ * It listens for choosers only while someone holds control: Playwright
116
+ * intercepts a page's choosers while anything listens, so the rest of the
117
+ * time a headed browser's own dialog opens as before, and an agent's
118
+ * chooser is left to Playwright MCP's browser_file_upload.
119
+ *
120
+ * Events:
121
+ * change (state) the chooser on offer changed; null when none is
122
+ * unavailable ({ reason }) a chooser opened that the live view may not answer
123
+ * progress ({ id, key, received, total }) an upload went on
124
+ * uploaded ({ id, user, files, bytes }) the files were set on the input
125
+ */
126
+ export class FileChooserRelay extends EventEmitter {
127
+ /**
128
+ * @param {object} options
129
+ * @param {import('playwright').BrowserContext} options.context
130
+ * @param {import('./control-lock.mjs').ControlLock} options.lock
131
+ * @param {string} options.dir where uploaded files are written
132
+ * @param {Partial<typeof DEFAULT_UPLOAD_LIMITS>} [options.limits]
133
+ * @param {number} [options.timeoutMs]
134
+ * @param {(message: string) => void} [options.log]
135
+ * @param {() => number} [options.now]
136
+ */
137
+ constructor({ context, lock, dir, limits = {}, timeoutMs = CHOOSER_TIMEOUT_MS, log = () => {}, now = Date.now }) {
138
+ super();
139
+ this.context = context;
140
+ this.lock = lock;
141
+ this.dir = dir;
142
+ this.limits = { ...DEFAULT_UPLOAD_LIMITS, ...limits };
143
+ this.timeoutMs = timeoutMs;
144
+ this.log = log;
145
+ this.now = now;
146
+ this.pending = null;
147
+ this.upload = null;
148
+ this.storedBytes = 0;
149
+ this.closed = false;
150
+ // Uploads, cancels and offers run one after another, as their messages
151
+ // arrive.
152
+ this.queue = Promise.resolve();
153
+ this.listening = false;
154
+ this.onChooser = (chooser) => void this.enqueue(() => this.offer(chooser));
155
+
156
+ lock.on('change', (holder, previous) => {
157
+ this.listen(Boolean(holder));
158
+ // A chooser an agent left open, waiting on browser_file_upload, is the
159
+ // person's to answer once they take over.
160
+ if (holder && !previous) void this.enqueue(() => this.adoptAgentChooser());
161
+ if (!holder) void this.enqueue(() => this.discard('control was handed back'));
162
+ else if (previous && this.upload?.key === previous.key) void this.enqueue(() => this.abortUpload());
163
+ });
164
+ }
165
+
166
+ // Follows the context's pages, to listen on them while someone holds
167
+ // control.
168
+ attach() {
169
+ this.context.on('page', (page) => {
170
+ if (this.listening) page.on('filechooser', this.onChooser);
171
+ });
172
+ this.listen(Boolean(this.lock.holder));
173
+ }
174
+
175
+ listen(on) {
176
+ if (on === this.listening || (on && this.closed)) return;
177
+ this.listening = on;
178
+ for (const page of this.context.pages()) {
179
+ if (on) page.on('filechooser', this.onChooser);
180
+ else page.off('filechooser', this.onChooser);
181
+ }
182
+ }
183
+
184
+ get enabled() {
185
+ return this.limits.maxFiles > 0;
186
+ }
187
+
188
+ // The chooser on offer, as viewers are told of it, or null.
189
+ get state() {
190
+ if (!this.pending) return null;
191
+ const { id, multiple, accept, since } = this.pending;
192
+ return { id, multiple, accept, since, max_files: multiple ? this.limits.maxFiles : 1, max_file_bytes: this.limits.maxFileBytes };
193
+ }
194
+
195
+ async offer(chooser, { adopted = false } = {}) {
196
+ if (this.closed || !this.lock.holder) return;
197
+ // Adopted from the agent's modal state, then seen opening too: it is the
198
+ // person's own.
199
+ if (this.pending?.chooser === chooser) {
200
+ if (!adopted) this.pending.adopted = false;
201
+ return;
202
+ }
203
+ if (!this.enabled) {
204
+ this.emit('unavailable', { reason: 'File uploads are turned off for this browser' });
205
+ return;
206
+ }
207
+
208
+ await this.discard(null);
209
+ const accept = await chooser.element().getAttribute('accept').catch(() => null);
210
+ this.pending = { id: randomUUID(), chooser, multiple: chooser.isMultiple(), accept: accept || null, since: this.now(), timer: null, adopted };
211
+ this.restartTimer();
212
+ this.emit('change', this.state);
213
+ }
214
+
215
+ // Offers the first file chooser an agent holds open, when none is on offer.
216
+ async adoptAgentChooser() {
217
+ if (this.closed || this.pending || !this.lock.holder || !this.enabled) return;
218
+ for (const page of this.context.pages()) {
219
+ const [chooser] = agentFileChoosers(page);
220
+ if (chooser) return this.offer(chooser, { adopted: true });
221
+ }
222
+ }
223
+
224
+ restartTimer() {
225
+ const pending = this.pending;
226
+ clearTimeout(pending.timer);
227
+ pending.timer = setTimeout(() => void this.enqueue(() => {
228
+ if (this.pending === pending) return this.discard('the file chooser timed out');
229
+ }), this.timeoutMs);
230
+ pending.timer.unref?.();
231
+ }
232
+
233
+ /**
234
+ * Starts answering the chooser `id` with `files` ({ name, size } each),
235
+ * for the connection `key`, which must hold control. The bytes follow in
236
+ * #chunk calls, in the order the files are listed. Resolves `{ done }`:
237
+ * true when every file is empty, so the input was set at once.
238
+ *
239
+ * @param {string} key
240
+ * @param {{ chooser: string, files: Array<{ name: string, size: number }> }} request
241
+ */
242
+ begin(key, request) {
243
+ return this.enqueue(async () => {
244
+ this.assertAnswering(key, request?.chooser);
245
+ const files = request.files;
246
+ const limit = this.state.max_files;
247
+ if (!Array.isArray(files) || files.length === 0) throw new UploadError('bad_upload', 'Choose at least one file');
248
+ if (files.length > limit) throw new UploadError('too_many', limit === 1 ? 'This field takes one file' : `This field takes at most ${limit} files`);
249
+ for (const file of files) {
250
+ if (!Number.isSafeInteger(file?.size) || file.size < 0) throw new UploadError('bad_upload', 'Each file needs its size in bytes');
251
+ if (file.size > this.limits.maxFileBytes) {
252
+ throw new UploadError('too_large', `${sanitizeFileName(file.name)} is larger than ${megabytes(this.limits.maxFileBytes)}`);
253
+ }
254
+ }
255
+ // Beginning again replaces an upload that did not finish.
256
+ await this.abortUpload();
257
+ const total = files.reduce((sum, file) => sum + file.size, 0);
258
+ if (this.storedBytes + total > this.limits.maxSessionBytes) {
259
+ throw new UploadError('too_large', `This browser takes at most ${megabytes(this.limits.maxSessionBytes)} of uploads in all`);
260
+ }
261
+
262
+ const root = join(this.dir, this.pending.id);
263
+ await mkdir(root, { recursive: true, mode: 0o700 });
264
+ const upload = { id: this.pending.id, key, root, total, received: 0, reported: 0, index: 0, files: [] };
265
+ this.upload = upload;
266
+ this.storedBytes += total;
267
+ try {
268
+ // A directory per file, so two files of the same name both arrive
269
+ // under it.
270
+ for (const [index, file] of files.entries()) {
271
+ const folder = join(root, String(index));
272
+ await mkdir(folder, { mode: 0o700 });
273
+ const path = join(folder, sanitizeFileName(file.name));
274
+ upload.files.push({ path, size: file.size, written: 0, handle: await open(path, 'wx', 0o600) });
275
+ }
276
+ } catch (error) {
277
+ await this.abortUpload();
278
+ throw error;
279
+ }
280
+ return { done: await this.advance() };
281
+ });
282
+ }
283
+
284
+ /**
285
+ * Writes the next chunk of the upload the connection `key` began, base64
286
+ * in `data`. Resolves `{ done, received, total }`; done once every file
287
+ * is written and set on the input.
288
+ *
289
+ * @param {string} key
290
+ * @param {{ chooser: string, data: string }} request
291
+ */
292
+ chunk(key, request) {
293
+ return this.enqueue(async () => {
294
+ this.assertAnswering(key, request?.chooser);
295
+ const upload = this.upload;
296
+ if (upload?.key !== key || upload.id !== request.chooser) throw new UploadError('bad_upload', 'Begin the upload before sending its files');
297
+
298
+ let bytes = decodeChunk(request.data);
299
+ if (upload.received + bytes.length > upload.total) {
300
+ await this.abortUpload();
301
+ throw new UploadError('bad_upload', 'More bytes arrived than the files hold');
302
+ }
303
+ this.restartTimer();
304
+ upload.received += bytes.length;
305
+ while (bytes.length > 0) {
306
+ const file = upload.files[upload.index];
307
+ const part = bytes.subarray(0, file.size - file.written);
308
+ await file.handle.write(part);
309
+ file.written += part.length;
310
+ bytes = bytes.subarray(part.length);
311
+ await this.advance();
312
+ }
313
+ if (upload.received - upload.reported >= PROGRESS_EVERY_BYTES) {
314
+ upload.reported = upload.received;
315
+ this.emit('progress', { id: upload.id, key, received: upload.received, total: upload.total });
316
+ }
317
+ return { done: upload.index === upload.files.length && this.upload !== upload, received: upload.received, total: upload.total };
318
+ });
319
+ }
320
+
321
+ /**
322
+ * Cancels the chooser `id` for the connection `key`, which must hold
323
+ * control: the input keeps what it had.
324
+ *
325
+ * @param {string} key
326
+ * @param {string} id
327
+ */
328
+ cancel(key, id) {
329
+ return this.enqueue(async () => {
330
+ this.assertAnswering(key, id);
331
+ await this.discard('cancelled');
332
+ });
333
+ }
334
+
335
+ assertAnswering(key, id) {
336
+ if (this.lock.holder?.key !== key) throw new UploadError('not_driving', 'Only the person driving the browser can choose its files');
337
+ if (!this.pending || this.pending.id !== id) throw new UploadError('no_chooser', 'That file chooser is no longer open');
338
+ }
339
+
340
+ // Closes the files written so far, and sets them on the input once all of
341
+ // them are. Returns whether it did.
342
+ async advance() {
343
+ const upload = this.upload;
344
+ while (upload.index < upload.files.length && upload.files[upload.index].written === upload.files[upload.index].size) {
345
+ await upload.files[upload.index].handle.close();
346
+ upload.index += 1;
347
+ }
348
+ if (upload.index < upload.files.length) return false;
349
+
350
+ const { chooser } = this.pending;
351
+ this.upload = null;
352
+ try {
353
+ await chooser.setFiles(upload.files.map((file) => file.path));
354
+ } catch (error) {
355
+ await this.discardFiles(upload);
356
+ await this.discard(null);
357
+ throw new UploadError('upload_failed', `The page did not take the files: ${error.message}`);
358
+ }
359
+ const user = this.lock.holder?.user ?? null;
360
+ this.log(`live view: ${upload.files.length} file(s), ${upload.total} bytes, set on a file input`);
361
+ this.emit('uploaded', { id: upload.id, user, files: upload.files.length, bytes: upload.total });
362
+ await this.discard(null, { answered: true });
363
+ return true;
364
+ }
365
+
366
+ // Stops the upload under way, removing what it wrote.
367
+ async abortUpload() {
368
+ const upload = this.upload;
369
+ if (!upload) return;
370
+ this.upload = null;
371
+ await this.discardFiles(upload);
372
+ }
373
+
374
+ async discardFiles(upload) {
375
+ for (const file of upload.files) await file.handle.close().catch(() => {});
376
+ await rm(upload.root, { recursive: true, force: true }).catch(() => {});
377
+ this.storedBytes -= upload.total;
378
+ }
379
+
380
+ // Withdraws the chooser on offer, and the upload under way for it. One
381
+ // adopted from an agent stays the agent's to answer unless the person did.
382
+ async discard(reason, { answered = false } = {}) {
383
+ const pending = this.pending;
384
+ if (!pending) return;
385
+ clearTimeout(pending.timer);
386
+ await this.abortUpload();
387
+ this.pending = null;
388
+ try {
389
+ if (answered || !pending.adopted) clearAgentFileChooser(pending.chooser.page(), pending.chooser);
390
+ } catch {
391
+ // The page closed.
392
+ }
393
+ if (reason) this.log(`live view: file chooser withdrawn (${reason})`);
394
+ this.emit('change', null);
395
+ }
396
+
397
+ enqueue(work) {
398
+ const run = this.queue.then(work);
399
+ this.queue = run.catch(() => {});
400
+ return run;
401
+ }
402
+
403
+ async close() {
404
+ this.closed = true;
405
+ this.listen(false);
406
+ await this.enqueue(() => this.discard(null));
407
+ }
408
+ }
409
+
410
+ function megabytes(bytes) {
411
+ return `${Math.round((bytes / (1024 * 1024)) * 10) / 10} MB`;
412
+ }
package/lib/guard.mjs CHANGED
@@ -34,9 +34,20 @@ function digest(value) {
34
34
  return createHash('sha256').update(value).digest();
35
35
  }
36
36
 
37
- function bearerMatches(header, token) {
37
+ /**
38
+ * The bearer token an Authorization header carries, or null.
39
+ *
40
+ * @param {string|undefined} header
41
+ * @returns {string|null}
42
+ */
43
+ export function bearerOf(header) {
38
44
  const match = /^Bearer\s+(\S+)\s*$/i.exec(header ?? '');
39
- return match !== null && timingSafeEqual(digest(match[1]), digest(token));
45
+ return match ? match[1] : null;
46
+ }
47
+
48
+ function bearerMatches(header, token) {
49
+ const presented = bearerOf(header);
50
+ return presented !== null && timingSafeEqual(digest(presented), digest(token));
40
51
  }
41
52
 
42
53
  /**
@@ -45,20 +56,24 @@ function bearerMatches(header, token) {
45
56
  * carry no Origin unless that origin is allowed (a page in a browser always
46
57
  * sends one), and carry the bearer token.
47
58
  *
59
+ * With `client` set, a live client token (ClientTokens) is accepted in place
60
+ * of the master token; the caller decides which paths allow that.
61
+ *
48
62
  * @param {import('node:http').IncomingMessage} request
49
63
  * @param {{ token: string, hosts: Set<string>, origins?: Set<string> }} rules
64
+ * @param {{ match(token: string): object|null } | null} [client] the client tokens to accept too
50
65
  * @returns {{ status: number, message: string } | null} the refusal, or null to proceed
51
66
  */
52
- export function refusal(request, { token, hosts, origins = new Set() }) {
67
+ export function refusal(request, { token, hosts, origins = new Set() }, client = null) {
53
68
  const host = (request.headers.host ?? '').toLowerCase();
54
69
  if (!hosts.has(host)) return { status: 403, message: 'Host not allowed' };
55
70
 
56
71
  const origin = request.headers.origin;
57
72
  if (origin !== undefined && !origins.has(origin)) return { status: 403, message: 'Origin not allowed' };
58
73
 
59
- if (!bearerMatches(request.headers.authorization, token)) return { status: 401, message: 'Missing or invalid bearer token' };
60
-
61
- return null;
74
+ if (bearerMatches(request.headers.authorization, token)) return null;
75
+ if (client?.match(bearerOf(request.headers.authorization))) return null;
76
+ return { status: 401, message: 'Missing or invalid bearer token' };
62
77
  }
63
78
 
64
79
  /**
@@ -1,6 +1,6 @@
1
1
  import http from 'node:http';
2
2
 
3
- import { liveRefusal, refusal } from './guard.mjs';
3
+ import { bearerOf, liveRefusal, refusal } from './guard.mjs';
4
4
  import { LIVE_PATH } from './live-server.mjs';
5
5
 
6
6
  // Larger than any tool call the engine sends.
@@ -56,6 +56,12 @@ function rejectUpgrade(socket, status) {
56
56
  * GET /live the live view's WebSocket (LiveServer), when `live` is given
57
57
  * GET /storage-state the browser's cookies and localStorage for the
58
58
  * app's origin, so a sign-in can be kept
59
+ * POST /tokens mints a client token ({ label }), for /mcp only (ClientTokens)
60
+ * DELETE /tokens/:id revokes one
61
+ *
62
+ * /mcp takes the master token or a live client token; a call made with a
63
+ * client token reaches the gateway tagged with that token's label. Every
64
+ * other endpoint takes the master token only.
59
65
  *
60
66
  * Every request, and every WebSocket upgrade other than the live view's, is
61
67
  * checked by guard.refusal before anything else happens. The live view's
@@ -69,16 +75,33 @@ function rejectUpgrade(socket, status) {
69
75
  * @param {string} options.version
70
76
  * @param {{ handleUpgrade: Function } | null} [options.live] a LiveServer
71
77
  * @param {() => Promise<object>} [options.storageState] returns what GET /storage-state answers
78
+ * @param {import('./client-tokens.mjs').ClientTokens | null} [options.clientTokens]
72
79
  * @returns {import('node:http').Server}
73
80
  */
74
- export function createHttpServer({ rules, gateway, version, live = null, storageState = null }) {
81
+ export function createHttpServer({ rules, gateway, version, live = null, storageState = null, clientTokens = null }) {
75
82
  const server = http.createServer(async (request, response) => {
76
- const denied = refusal(request, rules());
83
+ const path = pathOf(request);
84
+ const current = rules();
85
+ const denied = refusal(request, current, path === '/mcp' ? clientTokens : null);
77
86
  if (denied) return respond(response, denied.status, { error: denied.message });
78
87
 
79
- const path = new URL(request.url, 'http://sidecar').pathname;
80
88
  try {
81
89
  if (path === '/health' && request.method === 'GET') return respond(response, 200, { status: 'ok', version });
90
+ if (clientTokens && path === '/tokens' && request.method === 'POST') {
91
+ let body = {};
92
+ try {
93
+ body = JSON.parse((await readBody(request)) || '{}');
94
+ } catch (error) {
95
+ if (error.status) throw error;
96
+ return respond(response, 400, { error: 'The body is not JSON' });
97
+ }
98
+ return respond(response, 201, clientTokens.mint({ label: body?.label }));
99
+ }
100
+ const tokenId = /^\/tokens\/([0-9a-f-]{36})$/.exec(path ?? '')?.[1];
101
+ if (clientTokens && tokenId && request.method === 'DELETE') {
102
+ const revoked = clientTokens.revoke(tokenId);
103
+ return respond(response, revoked ? 200 : 404, revoked ? { revoked: true } : { error: 'Token not found' });
104
+ }
82
105
  if (path === '/storage-state' && request.method === 'GET' && storageState) {
83
106
  return respond(response, 200, { storage_state: await storageState() });
84
107
  }
@@ -99,7 +122,8 @@ export function createHttpServer({ rules, gateway, version, live = null, storage
99
122
  return respond(response, 400, { jsonrpc: '2.0', id: null, error: { code: -32700, message: 'The body is not JSON' } });
100
123
  }
101
124
 
102
- const result = await gateway.handle(message, typeof sessionId === 'string' ? sessionId : undefined);
125
+ const client = clientTokens?.match(bearerOf(request.headers.authorization)) ?? null;
126
+ const result = await gateway.handle(message, typeof sessionId === 'string' ? sessionId : undefined, client);
103
127
  return respond(response, result.status, result.body, result.headers);
104
128
  } catch (error) {
105
129
  if (!response.headersSent) respond(response, error.status ?? 500, { error: error.status ? error.message : 'Internal error' });
@@ -25,6 +25,7 @@ const MAX_BUFFERED_BYTES = 2 * 1024 * 1024;
25
25
  const CATCH_UP_MS = 250;
26
26
  const TERMINATE_AFTER_MS = 1000;
27
27
  const INPUT_TYPES = new Set(['mouse', 'wheel', 'key', 'text']);
28
+ const UPLOAD_TYPES = new Set(['file_upload', 'file_chunk', 'file_cancel']);
28
29
 
29
30
  function parse(data, isBinary) {
30
31
  if (isBinary) return null;
@@ -52,18 +53,31 @@ function parse(data, isBinary) {
52
53
  * { type: "take_control", ticket } a control ticket issued to the user the connection authenticated as
53
54
  * { type: "hand_back" }
54
55
  * mouse, wheel, key and text input see input.mjs; dropped unless this connection holds control
56
+ * { type: "file_upload", chooser, files: [{ name, size }] } answers the file chooser on offer (FileChooserRelay);
57
+ * { type: "file_chunk", chooser, data } then its files' bytes, in order, base64, at most
58
+ * 32 KiB each before encoding
59
+ * { type: "file_cancel", chooser } refused unless this connection holds control
55
60
  *
56
61
  * Sidecar to viewer:
57
- * { type: "ready", control, agent, page } once the ticket is accepted
62
+ * { type: "ready", control, agent, page, file_chooser, person_request } once the ticket is accepted
58
63
  * { type: "frame", data, width, height } a JPEG as base64, and the page's size in CSS pixels
59
64
  * { type: "control", held, mine, yours, by, since } who holds control, by name; mine when this
60
65
  * connection does, yours when its user does on any
61
- * { type: "agent", waiting, tool, since } an agent's call is waiting for control to be handed back
66
+ * { type: "agent", waiting, tool, since, client } an agent's call is waiting for control to be handed back;
67
+ * client names the agent ("Claude Code · turn 3"), or null
68
+ * { type: "person_requested", request } an agent asked for a person to take over:
69
+ * { reason, client, at }, or null once someone does
62
70
  * { type: "page", page: { url, tab, tabs } } the page on screen changed
71
+ * { type: "file_chooser", chooser } the page asked the person driving for files:
72
+ * { id, multiple, accept, since, max_files,
73
+ * max_file_bytes }, or null once answered or withdrawn
74
+ * { type: "file_upload", chooser, status, received, total, code, message }
75
+ * to the uploader: "progress", "done" or "failed"
63
76
  * { type: "error", code, message } a request this connection may not make
64
77
  *
65
- * Relayed input is never logged or recorded. Taking and handing back
66
- * control are, through `onMarker`.
78
+ * Relayed input is never logged or recorded, nor are the files a person
79
+ * uploads. Taking and handing back control are, through `onMarker`, and so
80
+ * is an upload's file count and size.
67
81
  */
68
82
  export class LiveServer {
69
83
  /**
@@ -71,15 +85,17 @@ export class LiveServer {
71
85
  * @param {{ verify(ticket: unknown): object }} options.verifier a TicketVerifier
72
86
  * @param {import('./control-lock.mjs').ControlLock} options.lock
73
87
  * @param {import('./screencast.mjs').Screencast} options.screencast
88
+ * @param {import('./file-upload.mjs').FileChooserRelay} [options.uploads] answers pages' file choosers
74
89
  * @param {(data: object) => void} [options.onMarker] given a takeover's start and end, to record
75
90
  * @param {(message: string) => void} [options.log]
76
91
  * @param {number} [options.authTimeoutMs] how long a connection may take to send its ticket
77
92
  * @param {number} [options.maxConnections]
78
93
  */
79
- constructor({ verifier, lock, screencast, onMarker = () => {}, log = () => {}, authTimeoutMs = AUTH_TIMEOUT_MS, maxConnections = MAX_CONNECTIONS }) {
94
+ constructor({ verifier, lock, screencast, uploads = null, onMarker = () => {}, log = () => {}, authTimeoutMs = AUTH_TIMEOUT_MS, maxConnections = MAX_CONNECTIONS }) {
80
95
  this.verifier = verifier;
81
96
  this.lock = lock;
82
97
  this.screencast = screencast;
98
+ this.uploads = uploads;
83
99
  this.onMarker = onMarker;
84
100
  this.log = log;
85
101
  this.authTimeoutMs = authTimeoutMs;
@@ -89,10 +105,21 @@ export class LiveServer {
89
105
  this.viewers = new Map();
90
106
  this.catchUp = null;
91
107
  this.closed = false;
108
+ this.personRequest = null;
92
109
 
93
110
  lock.on('change', (holder, previous, reason) => this.controlChanged(holder, previous, reason));
94
111
  lock.on('agent_waiting', () => this.broadcast({ type: 'agent', ...this.agentState() }));
95
112
  lock.on('agent_done', () => this.broadcast({ type: 'agent', ...this.agentState() }));
113
+ uploads?.on('change', (chooser) => this.broadcast({ type: 'file_chooser', chooser }));
114
+ uploads?.on('unavailable', ({ reason }) => {
115
+ const holder = this.holderViewer();
116
+ if (holder) this.send(holder, { type: 'error', code: 'uploads_off', message: reason });
117
+ });
118
+ uploads?.on('progress', ({ id, key, received, total }) => {
119
+ const viewer = [...this.viewers.values()].find((candidate) => candidate.id === key);
120
+ if (viewer) this.send(viewer, { type: 'file_upload', chooser: id, status: 'progress', received, total });
121
+ });
122
+ uploads?.on('uploaded', ({ user, files, bytes }) => this.onMarker({ label: 'file_uploaded', source: 'human', user, files, bytes }));
96
123
  }
97
124
 
98
125
  /**
@@ -144,7 +171,10 @@ export class LiveServer {
144
171
  this.viewers.set(ws, viewer);
145
172
  ws.on('message', (data, isBinary) => this.receive(viewer, parse(data, isBinary)));
146
173
 
147
- this.send(viewer, { type: 'ready', control: this.controlState(viewer), agent: this.agentState(), page: this.screencast.pageInfo });
174
+ this.send(viewer, {
175
+ type: 'ready', control: this.controlState(viewer), agent: this.agentState(), page: this.screencast.pageInfo,
176
+ file_chooser: this.uploads?.state ?? null, person_request: this.personRequest,
177
+ });
148
178
  if (this.screencast.lastFrame) this.sendFrame(viewer, JSON.stringify(frameMessage(this.screencast.lastFrame)));
149
179
  void this.screencast.start();
150
180
  }
@@ -155,6 +185,7 @@ export class LiveServer {
155
185
  if (message.type === 'take_control') this.takeControl(viewer, message.ticket);
156
186
  else if (message.type === 'hand_back') this.lock.release(viewer.id);
157
187
  else if (INPUT_TYPES.has(message.type)) this.relay(viewer, message);
188
+ else if (UPLOAD_TYPES.has(message.type)) void this.answerChooser(viewer, message);
158
189
  }
159
190
 
160
191
  // A ticket per request, rather than one per connection, means a person
@@ -179,6 +210,38 @@ export class LiveServer {
179
210
  this.screencast.dispatch(...command).catch(() => this.log(`live view: ${command[0]} was not delivered`));
180
211
  }
181
212
 
213
+ // A file chooser's answer, from the person driving: its files, their
214
+ // bytes, or a cancel. The relay refuses anyone else.
215
+ async answerChooser(viewer, message) {
216
+ if (!this.uploads) {
217
+ this.send(viewer, { type: 'error', code: 'uploads_off', message: 'File uploads are turned off for this browser' });
218
+ return;
219
+ }
220
+
221
+ const chooser = typeof message.chooser === 'string' ? message.chooser : null;
222
+ try {
223
+ if (message.type === 'file_cancel') {
224
+ await this.uploads.cancel(viewer.id, chooser);
225
+ return;
226
+ }
227
+ const result = message.type === 'file_upload'
228
+ ? await this.uploads.begin(viewer.id, { chooser, files: message.files })
229
+ : await this.uploads.chunk(viewer.id, { chooser, data: message.data });
230
+ if (result.done) this.send(viewer, { type: 'file_upload', chooser, status: 'done' });
231
+ } catch (error) {
232
+ if (!error.code) this.log(`live view: an upload failed: ${error.message}`);
233
+ this.send(viewer, {
234
+ type: 'file_upload', chooser, status: 'failed', code: error.code ?? 'upload_failed',
235
+ message: error.code ? error.message : 'The upload failed',
236
+ });
237
+ }
238
+ }
239
+
240
+ holderViewer() {
241
+ const key = this.lock.holder?.key;
242
+ return key ? [...this.viewers.values()].find((viewer) => viewer.id === key) ?? null : null;
243
+ }
244
+
182
245
  leave(ws) {
183
246
  const viewer = this.viewers.get(ws);
184
247
  if (!viewer) return;
@@ -198,12 +261,31 @@ export class LiveServer {
198
261
 
199
262
  agentState() {
200
263
  const waiting = this.lock.agentWaiting;
201
- return waiting ? { waiting: true, tool: waiting.tool, since: waiting.since } : { waiting: false, tool: null, since: null };
264
+ return waiting
265
+ ? { waiting: true, tool: waiting.tool, since: waiting.since, client: waiting.client ?? null }
266
+ : { waiting: false, tool: null, since: null, client: null };
267
+ }
268
+
269
+ /**
270
+ * Tells everyone watching that an agent asked for a person to take over
271
+ * (McpGateway's REQUEST_PERSON_TOOL). The request stands until someone
272
+ * takes control.
273
+ *
274
+ * @param {{ reason: string, client: string|null }} request
275
+ */
276
+ personRequested({ reason, client }) {
277
+ this.personRequest = { reason, client, at: Date.now() };
278
+ this.broadcast({ type: 'person_requested', request: this.personRequest });
279
+ this.onMarker({ label: 'person_requested', source: 'agent', client, reason });
202
280
  }
203
281
 
204
282
  // Control moving between connections of one user is no takeover of its own.
205
283
  controlChanged(holder, previous, reason) {
206
284
  for (const viewer of this.viewers.values()) this.send(viewer, { type: 'control', ...this.controlState(viewer) });
285
+ if (holder && this.personRequest) {
286
+ this.personRequest = null;
287
+ this.broadcast({ type: 'person_requested', request: null });
288
+ }
207
289
 
208
290
  if (holder && !previous) this.onMarker({ label: 'takeover_started', source: 'human', user: holder.user });
209
291
  else if (!holder && previous) this.onMarker({ label: 'takeover_ended', source: 'human', user: previous.user, reason });
@@ -39,6 +39,49 @@ function takeoverError(id, holder, waitedMs) {
39
39
  return result;
40
40
  }
41
41
 
42
+ // A tool the gateway answers itself: an agent asks for a person to take over
43
+ // the browser (a sign-in, a CAPTCHA, a file to upload). It returns at once,
44
+ // and the live view shows the request to whoever watches.
45
+ export const REQUEST_PERSON_TOOL = {
46
+ name: 'browser_request_person',
47
+ title: 'Ask a person to take over',
48
+ description: 'Ask the person watching this browser in the dashboard to take control and do something you cannot, ' +
49
+ 'such as signing in, solving a CAPTCHA or choosing a file to upload. Returns at once: end your turn and wait for ' +
50
+ 'their reply, which arrives as your next message.',
51
+ inputSchema: {
52
+ type: 'object',
53
+ properties: { reason: { type: 'string', description: 'What you need the person to do, in one sentence' } },
54
+ required: ['reason'],
55
+ additionalProperties: false,
56
+ },
57
+ annotations: { readOnlyHint: true, openWorldHint: false },
58
+ };
59
+ const MAX_REASON = 500;
60
+
61
+ function clock(at) {
62
+ return `${new Date(at).toISOString().slice(11, 19)} UTC`;
63
+ }
64
+
65
+ /**
66
+ * The note an agent's next tool result carries after people took or handed
67
+ * back control of the browser: what changed, and that the page may not be
68
+ * what it last saw.
69
+ *
70
+ * @param {Array<{ at: number, type: 'taken'|'released', reason: string, user: string|null }>} changes oldest first
71
+ * @param {object|null} holder who holds control now
72
+ * @returns {string}
73
+ */
74
+ export function handoffNote(changes, holder) {
75
+ const parts = changes.map((change) => {
76
+ const who = change.user ?? 'A person';
77
+ if (change.type === 'taken') return `${who} took control of the browser at ${clock(change.at)}`;
78
+ if (change.reason === 'disconnected') return `${who}'s control lapsed at ${clock(change.at)} when they disconnected`;
79
+ return `${who} handed it back at ${clock(change.at)}`;
80
+ });
81
+ const now = holder ? ` ${holder.user.name ?? 'A person'} is still driving it.` : '';
82
+ return `[dashboard] ${parts.join('; ')}.${now} The page may have changed: take a snapshot before acting.`;
83
+ }
84
+
42
85
  function isRequest(message) {
43
86
  return typeof message.method === 'string' && message.id !== undefined && message.id !== null;
44
87
  }
@@ -136,11 +179,14 @@ export class McpGateway {
136
179
  * @param {import('./control-lock.mjs').ControlLock} [options.lock]
137
180
  * @param {number} [options.agentWaitMs]
138
181
  * @param {(name: string, args: object) => void} [options.afterCall] told of each tool call that succeeded
182
+ * @param {((request: { reason: string, client: string|null }) => void) | null} [options.onPersonRequested]
183
+ * offers REQUEST_PERSON_TOOL, and is told of each call to it
139
184
  */
140
185
  constructor({
141
186
  connect, policy, deniedTools = DENIED_TOOLS, maxSessions = 8, idleMs = 30 * 60_000, requestTimeoutMs = 120_000, snapshotDir = null,
142
- guard = null, lock = null, agentWaitMs = 0, afterCall = () => {},
187
+ guard = null, lock = null, agentWaitMs = 0, afterCall = () => {}, onPersonRequested = null,
143
188
  }) {
189
+ this.onPersonRequested = onPersonRequested;
144
190
  this.connect = connect;
145
191
  this.policy = policy;
146
192
  this.guard = guard;
@@ -161,9 +207,10 @@ export class McpGateway {
161
207
  *
162
208
  * @param {unknown} message the parsed body
163
209
  * @param {string | undefined} sessionId the Mcp-Session-Id header
210
+ * @param {{ label: string|null } | null} [client] the client token the request came with, if not the master token
164
211
  * @returns {Promise<{ status: number, headers?: object, body?: object }>}
165
212
  */
166
- async handle(message, sessionId) {
213
+ async handle(message, sessionId, client = null) {
167
214
  if (!message || typeof message !== 'object' || Array.isArray(message) || message.jsonrpc !== JSONRPC) {
168
215
  return { status: 400, body: rpcError(null, -32600, 'The body must be one JSON-RPC 2.0 message') };
169
216
  }
@@ -179,6 +226,10 @@ export class McpGateway {
179
226
  return { status: 202 };
180
227
  }
181
228
 
229
+ if (message.method === 'tools/call' && this.onPersonRequested && message.params?.name === REQUEST_PERSON_TOOL.name) {
230
+ return { status: 200, body: this.requestPerson(message, client) };
231
+ }
232
+
182
233
  const inbound = this.inbound(message);
183
234
  if (inbound.answer) return { status: 200, body: inbound.answer };
184
235
 
@@ -188,7 +239,7 @@ export class McpGateway {
188
239
  const call = message.method === 'tools/call' ? inbound.message.params : null;
189
240
  if (call && this.lock) {
190
241
  const waitStarted = Date.now();
191
- const refusal = await this.lock.admit(call.name, call.arguments, this.agentWaitMs);
242
+ const refusal = await this.lock.admit(call.name, call.arguments, this.agentWaitMs, client?.label ?? null);
192
243
  if (refusal?.stopping) return { status: 200, body: toolError(message.id, 'The browser is stopping. Nothing was done.') };
193
244
  if (refusal) return { status: 200, body: takeoverError(message.id, refusal.holder, Date.now() - waitStarted) };
194
245
  }
@@ -199,7 +250,8 @@ export class McpGateway {
199
250
  if (refusal) return { status: 200, body: toolError(message.id, refusal) };
200
251
  if (call && response.result && !response.result.isError) this.afterCall(call.name, call.arguments);
201
252
 
202
- return { status: 200, body: await this.outbound(message, response) };
253
+ const body = await this.outbound(message, response);
254
+ return { status: 200, body: call ? this.withHandoffNote(session, body) : body };
203
255
  } finally {
204
256
  session.busy -= 1;
205
257
  this.touch(session);
@@ -218,7 +270,8 @@ export class McpGateway {
218
270
  await server.connect(transport);
219
271
 
220
272
  const id = randomUUID();
221
- const session = { server, transport, busy: 1 };
273
+ // A new session has seen every control change so far: it saw no page yet.
274
+ const session = { server, transport, busy: 1, journalSeen: this.lock?.journalSeq ?? 0 };
222
275
  this.touch(session);
223
276
  this.sessions.set(id, session);
224
277
  try {
@@ -234,6 +287,33 @@ export class McpGateway {
234
287
  }
235
288
  }
236
289
 
290
+ // Answers a call to REQUEST_PERSON_TOOL, and passes the request on.
291
+ requestPerson(message, client) {
292
+ const raw = message.params?.arguments?.reason;
293
+ const reason = typeof raw === 'string' ? raw.replace(/[\u0000-\u001f\u007f]/g, ' ').trim().slice(0, MAX_REASON) : '';
294
+ if (reason === '') return toolError(message.id, 'Say what you need the person to do, as reason');
295
+
296
+ this.onPersonRequested({ reason, client: client?.label ?? null });
297
+ const text = 'Asked the person watching this browser. End your turn now and wait: their reply arrives as your next message, ' +
298
+ 'and the browser may have changed by then.';
299
+ return { jsonrpc: JSONRPC, id: message.id, result: { content: [{ type: 'text', text }] } };
300
+ }
301
+
302
+ // `body`, a tool call's answer to `session`, with a note ahead of its
303
+ // content when people took or handed back control since that session's
304
+ // last call.
305
+ withHandoffNote(session, body) {
306
+ if (!this.lock) return body;
307
+ const changes = this.lock.changesSince(session.journalSeen);
308
+ if (changes.length === 0) return body;
309
+
310
+ session.journalSeen = this.lock.journalSeq;
311
+ const content = Array.isArray(body.result?.content) ? body.result.content : null;
312
+ if (!content) return body;
313
+ const note = { type: 'text', text: handoffNote(changes, this.lock.holder) };
314
+ return { ...body, result: { ...body.result, content: [note, ...content] } };
315
+ }
316
+
237
317
  // The message as the server should see it, or the answer to give without
238
318
  // asking the server at all.
239
319
  inbound(message) {
@@ -258,7 +338,8 @@ export class McpGateway {
258
338
 
259
339
  async outbound(request, response) {
260
340
  if (request.method === 'tools/list' && Array.isArray(response.result?.tools)) {
261
- const tools = response.result.tools.filter((tool) => !this.deniedTools.has(tool.name));
341
+ const tools = response.result.tools.filter((tool) => !this.deniedTools.has(tool.name) && tool.name !== REQUEST_PERSON_TOOL.name);
342
+ if (this.onPersonRequested) tools.push(REQUEST_PERSON_TOOL);
262
343
  return { ...response, result: { ...response.result, tools } };
263
344
  }
264
345
  if (request.method === 'tools/call' && this.snapshotDir && Array.isArray(response.result?.content)) {
package/lib/sidecar.mjs CHANGED
@@ -2,7 +2,9 @@ import { mkdtemp, realpath, rm } from 'node:fs/promises';
2
2
  import { tmpdir } from 'node:os';
3
3
  import { join } from 'node:path';
4
4
 
5
+ import { ClientTokens } from './client-tokens.mjs';
5
6
  import { ControlLock } from './control-lock.mjs';
7
+ import { FileChooserRelay } from './file-upload.mjs';
6
8
  import { startEgressProxy } from './egress-proxy.mjs';
7
9
  import { acceptedHosts } from './guard.mjs';
8
10
  import { createHttpServer } from './http-server.mjs';
@@ -97,17 +99,19 @@ export function mcpConfig(config, outputDir) {
97
99
  *
98
100
  * @param {object} config a parsed configuration with `live` set
99
101
  * @param {import('playwright').BrowserContext} context
100
- * @param {{ recorder: Recorder | null, log: (message: string) => void }} options
101
- * @returns {Promise<{ server: LiveServer, lock: ControlLock, screencast: Screencast }>}
102
+ * @param {{ recorder: Recorder | null, uploadsDir: string, log: (message: string) => void }} options
103
+ * @returns {Promise<{ server: LiveServer, lock: ControlLock, screencast: Screencast, uploads: FileChooserRelay }>}
102
104
  */
103
- async function startLiveView(config, context, { recorder, log }) {
105
+ async function startLiveView(config, context, { recorder, uploadsDir, log }) {
104
106
  const lock = new ControlLock({ graceMs: config.live.releaseGraceMs });
105
107
  const verifier = new TicketVerifier({ key: ticketKey(config.token), sessionId: config.live.sessionId });
106
108
  let server = null;
107
109
  const screencast = new Screencast({ context, log, onFrame: (frame) => server?.frame(frame), onPageChange: () => server?.pageChanged() });
108
- server = new LiveServer({ verifier, lock, screencast, log, onMarker: (data) => recorder?.marker(data) });
110
+ const uploads = new FileChooserRelay({ context, lock, dir: uploadsDir, limits: config.live.uploadLimits, log });
111
+ server = new LiveServer({ verifier, lock, screencast, uploads, log, onMarker: (data) => recorder?.marker(data) });
112
+ uploads.attach();
109
113
  await screencast.attach();
110
- return { server, lock, screencast };
114
+ return { server, lock, screencast, uploads };
111
115
  }
112
116
 
113
117
  /**
@@ -116,7 +120,9 @@ async function startLiveView(config, context, { recorder, log }) {
116
120
  * (Playwright's --remote-debugging-pipe), so no debugging port is opened.
117
121
  * Every connection it makes goes through the egress proxy, loopback and
118
122
  * WebRTC included. The process's working directory becomes an empty uploads
119
- * directory, which is where Playwright MCP reads files to upload from.
123
+ * directory, which is where Playwright MCP reads files to upload from. The
124
+ * files a person uploads through the live view go to a directory of their
125
+ * own.
120
126
  *
121
127
  * @param {object} config a parsed configuration (see parseConfig)
122
128
  * @param {object} [dependencies]
@@ -139,8 +145,9 @@ export async function startSidecar(config, dependencies = {}) {
139
145
  const profileDir = await mkdtemp(join(workdir, 'profile-'));
140
146
  const uploadsDir = await mkdtemp(join(workdir, 'uploads-'));
141
147
  const outputDir = await mkdtemp(join(workdir, 'output-'));
148
+ const liveUploadsDir = await mkdtemp(join(workdir, 'live-uploads-'));
142
149
  const removeDirectories = async () => {
143
- for (const dir of ownsWorkdir ? [workdir] : [profileDir, uploadsDir, outputDir]) {
150
+ for (const dir of ownsWorkdir ? [workdir] : [profileDir, uploadsDir, outputDir, liveUploadsDir]) {
144
151
  await rm(dir, { recursive: true, force: true }).catch(() => {});
145
152
  }
146
153
  };
@@ -177,7 +184,7 @@ export async function startSidecar(config, dependencies = {}) {
177
184
  guard.attach(context);
178
185
  const recorder = config.recording ? new Recorder({ recording: config.recording, log }) : null;
179
186
  await recorder?.attach(context);
180
- const live = config.live ? await startLiveView(config, context, { recorder, log }) : null;
187
+ const live = config.live ? await startLiveView(config, context, { recorder, uploadsDir: liveUploadsDir, log }) : null;
181
188
 
182
189
  const gateway = new McpGateway({
183
190
  connect: () => connect(mcpConfig(config, outputDir), async () => context),
@@ -186,6 +193,7 @@ export async function startSidecar(config, dependencies = {}) {
186
193
  snapshotDir: await realpath(outputDir),
187
194
  lock: live?.lock,
188
195
  agentWaitMs: config.live?.agentWaitMs,
196
+ onPersonRequested: live ? (request) => live.server.personRequested(request) : null,
189
197
  afterCall: (name, args) => {
190
198
  // Playwright MCP numbers tabs from 0 in the order they opened, as context.pages() lists them.
191
199
  if (live && name === 'browser_tabs' && args?.action === 'select' && Number.isInteger(args.index)) void live.screencast.followIndex(args.index);
@@ -193,12 +201,14 @@ export async function startSidecar(config, dependencies = {}) {
193
201
  });
194
202
  let hosts = new Set();
195
203
  const liveOrigins = new Set(config.live?.origins ?? []);
204
+ const clientTokens = new ClientTokens();
196
205
  const server = createHttpServer({
197
206
  rules: () => ({ token: config.token, hosts, liveOrigins }),
198
207
  gateway,
199
208
  version: VERSION,
200
209
  live: live?.server,
201
210
  storageState: () => exportStorageState(context, config.appOrigin),
211
+ clientTokens,
202
212
  });
203
213
 
204
214
  let closing = null;
@@ -214,6 +224,7 @@ export async function startSidecar(config, dependencies = {}) {
214
224
  server.close();
215
225
  server.closeAllConnections();
216
226
  live?.server.close();
227
+ await live?.uploads.close();
217
228
  await live?.screencast.close();
218
229
  await gateway.closeAll();
219
230
  // The pages hand over the rrweb events they hold, then the context
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@activeagents/browser-sidecar",
3
- "version": "1.9.2",
3
+ "version": "1.9.3",
4
4
  "description": "One sandbox's browser for the Active Agent dashboard: Chromium driven over Playwright MCP, recorded with rrweb.",
5
5
  "license": "MIT",
6
6
  "type": "module",