qz-browser-agent 0.1.1 → 0.1.2

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
@@ -1,467 +1,126 @@
1
- # qz command line and MCP
1
+ # qz
2
2
 
3
- Run browser tasks, manage results, and connect external agents to qz through CLI or MCP.
4
- Requires Node.js 24 or later and Chrome. CLI and MCP share the same browser connection.
3
+ An open-source browser agent for humans and coding agents.
5
4
 
6
- ## Quick start
7
-
8
- Install [qz from the Chrome Web Store](https://chromewebstore.google.com/detail/dknbdgkgoinlgjpfebapkklbmjjgdblm)
9
- with **Add to Chrome**. Open the qz side panel, complete its first-use data notice, and configure
10
- your provider and model in Settings.
11
-
12
- Run the published package with npx:
13
-
14
- ```bash
15
- npx qz-browser-agent@latest connect
16
- npx qz-browser-agent@latest create "Summarize the current page." --stream
17
- ```
18
-
19
- `npx qz-browser-agent@latest install` opens the same Chrome Web Store page. For a manual ZIP
20
- installation, download the [latest GitHub release](https://github.com/alibaba/qz-browser-agent/releases/latest)
21
- and follow the [manual installation steps](https://github.com/alibaba/qz-browser-agent/blob/main/README.md#manual-installation).
22
-
23
- `connect` starts the local MCP service and opens its connection page for first pairing. Use the
24
- Chrome profile where qz is installed. The first new profile is named `default`;
25
- accepting the data notice alone does not enable the local connection. Repeating `connect` reuses
26
- an online browser. Add further profiles with a [pairing URL](#pair-a-selected-browser-from-the-shell)
27
- or from their own qz Settings.
28
-
29
- The examples and suggested next commands use `qz`. Replace it with
30
- `npx qz-browser-agent@latest`, or install the command globally:
31
-
32
- ```sh
33
- npm install --global qz-browser-agent@latest
34
- qz --version
35
- ```
36
-
37
- On Windows, use PowerShell 7.3 or newer with its default native argument passing. After a global
38
- install, use `qz.ps1` for commands containing JSON or quoted names; Windows command suggestions
39
- use that wrapper. For automation, pin a compatible release version verified with your extension.
5
+ qz is a local-first extension for Chrome and Edge.
6
+ People use it from the side panel; agents such as Claude Code, Codex, and pi hand it web tasks
7
+ through this CLI or MCP. qz works in your own browser, with your existing logins, and returns
8
+ tables, files, or reports with sources. Everything runs locally, and your data goes only to the
9
+ model you choose.
40
10
 
41
- ## Connect and stop
42
-
43
- ```bash
44
- qz connect
45
- qz status
46
- qz browsers
47
- qz mcp
48
- qz stop
49
- ```
11
+ [Website](https://alibaba.github.io/qz-browser-agent/) ·
12
+ [GitHub](https://github.com/alibaba/qz-browser-agent) ·
13
+ [Chrome Web Store](https://chromewebstore.google.com/detail/dknbdgkgoinlgjpfebapkklbmjjgdblm) ·
14
+ [Full CLI and MCP reference](https://github.com/alibaba/qz-browser-agent/blob/main/docs/cli.md)
50
15
 
51
- `connect` reuses the healthy service already running for this installation. It prefers port 18765;
52
- if that port belongs to another program, the service chooses a free port. `status` shows the actual
53
- service address, and `mcp` prints its MCP URL. Both commands are read-only. To request a custom port,
54
- run `qz connect --port 18766`; an existing service on another port remains running and the command
55
- reports its address. The extension connects only to its configured address.
16
+ ![A coding agent handing a GitHub research task to qz](https://raw.githubusercontent.com/alibaba/qz-browser-agent/main/docs/images/examples/en/pi-delegate-en.gif)
56
17
 
57
- The connection page can be closed once `qz browsers` shows the profile online. Connections start
58
- only through `qz connect` or **qz Settings → Advanced → CLI → Connect CLI**. For ordinary connection
59
- failures, the extension makes at most three recovery attempts, 30 seconds apart, then pauses.
60
- After a browser or background restart, it may first wait once for the previous connection to expire.
61
- The saved retry budget survives worker restarts. Click **Connect CLI** in that browser's settings to retry.
62
-
63
- To disconnect one browser, click **Disconnect: NAME** in its qz Settings. `qz stop` stops the local
64
- service and disconnects every browser and MCP client using it. Browser tasks already running
65
- remain in the extension; stopping the service does not cancel them. Use `qz cancel TASK_ID` to stop
66
- a task, adding `--client NAME|UUID` when needed.
67
-
68
- ### Pair a selected browser from the shell
69
-
70
- Get a pairing URL without opening the default browser or waiting for a connection:
71
-
72
- ```bash
73
- qz connect --no-open --json
74
- qz connect --no-open --name work --json
75
- ```
76
-
77
- The JSON envelope contains `result.endpoint`, `result.url`, `result.mcpUrl`, and
78
- `result.opened: false`. The command starts or reuses the service even when other browsers are
79
- already connected. Open the exact returned URL in the intended browser Profile with qz installed.
80
-
81
- Set `QZ_PAIRING_URL` to that URL and `QZ_PROFILE_DIRECTORY` to the selected profile's directory
82
- name, such as `Default` or `Profile 2`. These are directory names, not Chrome's display labels.
83
- Use a Profile already chosen by the user. On macOS:
84
-
85
- ```sh
86
- open -na "Google Chrome" --args --profile-directory="$QZ_PROFILE_DIRECTORY" "$QZ_PAIRING_URL"
87
- ```
88
-
89
- For Chrome on Linux:
18
+ ## Quick start
90
19
 
91
- ```sh
92
- google-chrome --profile-directory="$QZ_PROFILE_DIRECTORY" "$QZ_PAIRING_URL"
93
- ```
20
+ Requires Node.js 22 or later.
94
21
 
95
- For Chrome installed under Program Files on Windows, set `$QzProfileDirectory` and
96
- `$QzPairingUrl` to those same values in PowerShell:
22
+ 1. **Install the extension.** Click **Add to Chrome** on the
23
+ [Chrome Web Store](https://chromewebstore.google.com/detail/dknbdgkgoinlgjpfebapkklbmjjgdblm),
24
+ open the qz side panel, and choose a provider and model in **Settings**.
25
+ 2. **Connect.** This starts the local service and pairs automatically with your default browser.
97
26
 
98
- ```powershell
99
- & "$env:ProgramFiles\Google\Chrome\Application\chrome.exe" "--profile-directory=$QzProfileDirectory" $QzPairingUrl
100
- ```
27
+ ```bash
28
+ npx qz-browser-agent@latest connect
29
+ ```
101
30
 
102
- Use the installed browser's executable or app name. For an existing custom data directory, also
103
- pass `--user-data-dir` with its exact path; for example on macOS:
31
+ 3. **Run your first task.**
104
32
 
105
- ```sh
106
- open -na "Google Chrome" --args --user-data-dir="$QZ_USER_DATA_DIR" --profile-directory="$QZ_PROFILE_DIRECTORY" "$QZ_PAIRING_URL"
107
- ```
33
+ ```bash
34
+ npx qz-browser-agent@latest create "Find this year's Nobel Prize winners in every category and put them in a table with source links." --stream
35
+ ```
108
36
 
109
- The [Chrome profile documentation](https://chromium.googlesource.com/chromium/src/+/master/docs/user_data_dir.md)
110
- distinguishes the data directory from the Profile inside it. A new data directory needs its own
111
- extension installation and first-use setup.
37
+ `--stream` shows progress, any questions qz needs you to answer, and the final result.
112
38
 
113
- `--name work` adds `?name=work` to the URL. The Profile opening it receives that identifier,
114
- including when it already has a connection. Without `--name`, a registered Profile keeps its name;
115
- a new Profile receives the next available name: `default`, `browser-2`, and so on. A name conflict
116
- requires another name. `qz connect --name work` opens the URL automatically and returns immediately.
117
- These URL-returning commands do not confirm that a browser connected. Verify it with:
39
+ For regular use, install the `qz` command globally and use it in place of
40
+ `npx qz-browser-agent@latest`:
118
41
 
119
42
  ```bash
120
- qz browsers --json
121
- qz create "Summarize the current page." --client UUID --stream
43
+ npm install --global qz-browser-agent@latest
44
+ qz --version
122
45
  ```
123
46
 
124
- Read `result.browsers`, then use the intended online entry's `clientId` UUID. `--client` selects an
125
- existing connection and cannot be combined with `--no-open` or `--name`. `--port` works with either
126
- pairing mode and follows the existing-service behavior above.
127
-
128
- ### Add and select browsers
129
-
130
- You can also pair from **qz Settings → Advanced → CLI** in the intended Profile. Enter a distinct
131
- browser identifier and connect. Use the service address printed by `qz status` in **Local service address** if
132
- its port differs from 18765. Names use 1–64 letters, digits, underscores, or hyphens, beginning with
133
- a letter or digit; names are case-sensitive. UUID-shaped names are reserved for profile IDs.
134
-
135
- ```bash
136
- qz browsers
137
- qz create "Summarize the current page." --client work --stream
138
- qz show TASK_ID --client work
139
- qz data --client work
140
- ```
47
+ To let your agent learn when and how to use qz, install the Skill with
48
+ `npx skills add alibaba/qz-browser-agent -g`.
141
49
 
142
- `--client NAME|UUID` and `-c NAME|UUID` select a profile. With exactly one online browser, the CLI
143
- selects it automatically. With several online browsers, a selection is required; `default` is a
144
- name, not a routing preference. An unknown or offline selection fails without opening or using
145
- another browser. Each command resolves its name once and carries the UUID through subsequent
146
- requests. JSON task results and suggested next commands include that UUID.
50
+ ## Connect an MCP client
147
51
 
148
- Names remain registered while their browsers are offline and across service restarts. To release
149
- an offline name, remove its registration explicitly:
52
+ After `connect`, print the MCP URL:
150
53
 
151
54
  ```bash
152
- qz browsers forget work
55
+ npx qz-browser-agent@latest mcp
153
56
  ```
154
57
 
155
- An online browser must first disconnect in its settings. Forgetting a registration leaves the
156
- browser's tasks and data intact. A browser can then explicitly pair using the released name.
157
-
158
- ### Update the connection
58
+ The default is `http://127.0.0.1:18765/mcp`; use the URL your command prints if the port differs.
159
59
 
160
- Use the current CLI and extension together. Source edits and a newer npm package leave a healthy
161
- running service in place; `qz status` reports an available update. An incompatible service returns
162
- an update instruction instead of being stopped automatically.
163
-
164
- 1. Use the latest CLI and let current tasks finish.
165
- 2. Run `npx --yes qz-browser-agent@latest stop`. This disconnects all browsers using that service.
166
- 3. Update qz from the [Chrome Web Store](https://chromewebstore.google.com/detail/dknbdgkgoinlgjpfebapkklbmjjgdblm).
167
- For a manual ZIP installation, replace its extracted files with the
168
- [latest release](https://github.com/alibaba/qz-browser-agent/releases/latest) and reload it at `chrome://extensions`.
169
- 4. Run `npx --yes qz-browser-agent@latest connect`, then reconnect additional profiles using their
170
- pairing URL or settings.
171
-
172
- ## Connect an MCP client
173
-
174
- Run `qz connect`, then `qz mcp`. Copy the returned URL into your MCP client's HTTP configuration:
60
+ **Codex** (`~/.codex/config.toml`):
175
61
 
176
62
  ```toml
177
63
  [mcp_servers.qz]
178
64
  url = "http://127.0.0.1:18765/mcp"
179
65
  ```
180
66
 
181
- Use the URL printed by your command if its port differs. `qz mcp --json` returns the URL as JSON
182
- for scripts. The `qingzhou_*` MCP tool names and extension protocol remain available. Responses
183
- to pending input bind to an explicit `waitId`. Use `qingzhou_bridge_status` to list browser names
184
- and UUIDs, then pass `clientId: "work"` or a UUID to browser tools. Selection is required with
185
- multiple online browsers. Task results include the resolved `clientId`. MCP initialization and streaming are handled by your
186
- client's MCP implementation.
187
-
188
- ### Task and resource operations
189
-
190
- CLI and MCP use the same task observer and browser operations. The task and resource commands map to these MCP operations:
191
-
192
- | CLI | MCP tool |
193
- | --- | --- |
194
- | `browsers`, `browsers forget` | `qingzhou_bridge_status`, `qingzhou_forget_browser` |
195
- | `create`, `send`, `cancel` | `qingzhou_create_session`, `qingzhou_send_message`, `qingzhou_stop_session` |
196
- | `tasks`, `show`, `watch` | `qingzhou_list_sessions`, `qingzhou_get_session_snapshot`, `qingzhou_watch_task` |
197
- | `show`, `submit` / `approve` / `reject` | `qingzhou_get_session_snapshot`, `qingzhou_respond_to_user_input` |
198
- | `data list` / `delete` / `export` | `qingzhou_list_data_tables`, `qingzhou_delete_data_table`, `qingzhou_export_data_table` |
199
- | `images list` / `delete` / `export` | `qingzhou_list_image_collections`, `qingzhou_delete_image_collection`, `qingzhou_export_image_collection` |
200
- | `skills list` / `show` / `read` / `tools` / `export` | `qingzhou_list_skills`, `qingzhou_get_skill`, `qingzhou_get_skill_resource`, `qingzhou_list_plugins`, `qingzhou_export_skill` |
201
- | `settings get` / `set` | `qingzhou_get_settings`, `qingzhou_update_settings` |
202
- | `automations list` / `run` | `qingzhou_list_automations`, `qingzhou_run_automation` |
203
-
204
- MCP creation, message submission, and input responses accept `wait: true` to wait for completion;
205
- `stream: true` also sends assistant text through standard MCP progress notifications. A watch call
206
- always waits. For example, call `qingzhou_create_session` with:
207
-
208
- ```json
209
- {"firstMessage":"Summarize the current page.","stream":true}
210
- ```
211
-
212
- Supply `_meta.progressToken` on the MCP request to receive progress. Each notification includes a
213
- readable `message` and its structured event in `params._meta["qz/task-event"]`. Events include
214
- `created`, `status`, `text`, `replace`, and `input`. Input events include the current form, exact
215
- field IDs, option values, and `responseTemplate`. Fill that template and pass it to
216
- `qingzhou_respond_to_user_input`; another CLI or MCP connection can answer while the original call
217
- keeps waiting. Native Chrome permissions still require the user's click in the side panel.
218
-
219
- MCP `timeoutSeconds` bounds each browser request (180 seconds by default).
220
- `waitTimeoutSeconds` bounds the whole observation; omit it for no overall deadline. Configure your
221
- MCP client's own request deadline for long tasks. On timeout or cancellation, the browser task
222
- continues; error details include the task ID and a recovery tool call. `send_message` supports
223
- `steer: true` and follows its returned `clientMessageId`, including when steering stays in the same
224
- run. A long observation stays bound to the browser selected when it started.
225
-
226
- ## Run a task
227
-
228
- ```bash
229
- qz create "Compare these two laptops."
230
- qz create "Summarize the current page." --title "Research" --wait
231
- qz create "Find the main differences between these pages." --stream
232
- qz send TASK_ID "Add the source links." --stream
233
- qz send TASK_ID "Focus on open-source options." --steer --stream
234
- qz tasks
235
- qz show TASK_ID
236
- qz cancel TASK_ID
237
- ```
238
-
239
- `create` starts a task and returns its ID. The title is optional. `--wait` waits for the result;
240
- `--stream` also displays progress as it arrives. Both stay connected while the task waits for user
241
- input and continue automatically after you respond. Task observation has no default time limit.
242
- Add `--timeout SECONDS` to set a total deadline, including time spent waiting for input. Each
243
- individual connection request remains bounded (180 seconds by default). A timeout or Ctrl-C ends
244
- watching; `qz watch TASK_ID --stream` resumes observation and `qz cancel TASK_ID` stops the task.
245
- Each CLI command initializes one MCP connection on its first tool call and reuses it for subsequent
246
- reads and responses. Completion, errors, and Ctrl-C close that connection. Transport failures are
247
- reported without automatically repeating browser actions.
248
-
249
- Provide the task text directly after `create`, or read it from stdin with `qz create -`.
250
- Use `--parent TASK_ID` to create a child task, and `qz tasks --limit N` to limit the task list.
251
- `send TASK_ID MESSAGE` sends a follow-up to the specified task; `qz send TASK_ID -` reads the message
252
- from stdin. A busy task queues a follow-up for its next run. Add `--steer` to deliver the message
253
- to the current run at its next safe boundary. Both start a new run when the task is idle. Pending
254
- questions and permissions still require a response.
255
-
256
- `--wait` and `--stream` track the submitted message. Streaming starts after that message, including
257
- when steering continues the same run. Pending questions from the preceding run remain visible so
258
- you can answer them and let a queued follow-up proceed. A connection failure never resends a message
259
- automatically.
260
-
261
- ## Respond to a task
262
-
263
- ```bash
264
- qz show TASK_ID
265
- qz submit TASK_ID '{"selectedIds":["option-a"]}' --stream
266
- qz approve TASK_ID --wait
267
- qz reject TASK_ID
268
- qz watch TASK_ID --stream
269
- ```
270
-
271
- `show` and pending-input notices include the current question, labeled field IDs,
272
- option values, descriptions, image URLs, and a submission template with the actual field IDs.
273
- Edit its placeholder values and run the displayed command to respond. `submit` takes a JSON object
274
- keyed by field IDs; use option values for choices and arrays for multiple choices. Use
275
- `qz submit TASK_ID -` to read answers from stdin. Invalid or stale submissions return the current
276
- input and its template so you can correct the response directly.
277
- `approve` continues a confirmation after you finish the requested action. `reject` declines the
278
- current request; `cancel` stops the whole task.
279
-
280
- Each response reads the current wait ID before sending. To answer a specific request you already
281
- read, pass `--wait-id WAIT_ID` to `submit`, `approve`, or `reject`. A stale or invalid response
282
- leaves the request pending. Review the application consent notice included in the pending input,
283
- such as location sharing, before approving. Native Chrome permissions require a click in the qz side panel; CLI
284
- approval reports that action is needed and preserves the wait without opening a browser page.
285
- With `--wait` or `--stream`, the command stays connected while you grant permission in Chrome.
286
- Location approval reads the current disclosure version and includes it in the response. Human
287
- terminal output shows the notice before submitting the explicit approval; JSON output remains a
288
- single final result. MCP callers should show the notice to the user before sending approval with
289
- the returned `consentVersion`.
290
-
291
- `submit`, `approve`, and `reject` accept `--wait` and `--stream` to follow the task until it finishes, including
292
- further questions and permission requests. Each new request is shown once. Respond in the side
293
- panel or another terminal; the original command continues automatically. `watch` follows an
294
- existing task without resubmitting anything. Timeouts and Ctrl-C stop watching, while the task
295
- continues in the browser.
296
-
297
- ## Browser selection and MCP tools
298
-
299
- Use `--client NAME|UUID` or `-c NAME|UUID` to select a browser. `qz browsers` lists registered names,
300
- UUIDs, and online status. See [browser selection](#add-and-select-browsers) for pairing and name reuse.
301
- Use `-t` for `--title`. Run `qz help COMMAND` or `qz COMMAND --help` for command-specific options.
302
-
303
- MCP clients can inspect browser tool schemas with `qingzhou_list_tools` and `qingzhou_get_tool`,
304
- then call `qingzhou_execute_tool` in a task. Set `wait: false` to receive a job ID and read the result
305
- with `qingzhou_get_tool_job`. Pass `runId` to bind execution to a particular task run. MCP also
306
- provides `qingzhou_get_trace` and `qingzhou_clear_trace` for diagnostics.
307
-
308
- If a request times out or its connection is interrupted, an operation already started in the
309
- browser may still be running. Check the task before repeating it. Disconnected MCP requests are
310
- cancelled in the service, and reconnecting does not replay their browser actions.
311
-
312
- ## Data, images, and Skills
313
-
314
- ```bash
315
- qz data
316
- qz data export TABLE
317
- qz data export TABLE --format csv
318
- qz data delete TABLE
319
- qz images
320
- qz images export COLLECTION
321
- qz images delete COLLECTION
322
- qz skills --query research
323
- qz skills show NAME
324
- qz skills read NAME scripts/run.js --limit 20000
325
- qz skills tools --session TASK_ID
326
- qz skills export NAME
327
- ```
328
-
329
- Use the exact names printed by each list; quote names containing spaces. Data exports default to
330
- Excel (`xlsx`); `--format csv` selects CSV. Image collections export as a ZIP containing available
331
- image files and metadata. Missing local images are reported in the result. Skill exports contain
332
- one user-installed Skill and its resources; built-in Skills require the extension and cannot be
333
- exported independently.
334
-
335
- `skills show` includes the resource paths. `skills read NAME PATH` reads one resource, with a
336
- default limit of 20,000 characters. Use `--start` and `--limit` to select a chunk; truncated text
337
- includes the command for the next chunk. `skills tools` lists contributed tools and whether they
338
- are active in the selected task's context.
339
- `skills --scope all|global|site|resident` filters by activation scope. Exports accept `--filename NAME`.
340
- `automations --limit N` limits the automation list.
341
-
342
- Exports use Chrome downloads. The result includes the download status, ID, filename, and path when
343
- Chrome provides it. Check pending downloads in `chrome://downloads`. `delete` removes the named table
344
- or image collection and its rows. Image blobs shared by other collections or task history remain
345
- in the asset store.
346
-
347
- ## Settings and automations
67
+ **Claude Code**:
348
68
 
349
69
  ```bash
350
- qz settings
351
- qz settings get model
352
- qz settings set model MODEL_ID
353
- qz settings set vision true
354
- qz settings set '{"modelParameters":{"temperature":0.5}}'
355
- qz settings set - < settings.json
356
- qz automations
357
- qz automations run AUTOMATION_ID
70
+ claude mcp add --transport http qz http://127.0.0.1:18765/mcp
358
71
  ```
359
72
 
360
- `settings` returns current values, editable fields, provider IDs, and protocol IDs. Credentials are
361
- redacted; `qz settings get apiKey` reports whether a key is configured. `set KEY VALUE` parses JSON
362
- values such as booleans, numbers, objects, and arrays; other values are strings. `set JSON` applies
363
- a patch containing the supplied top-level fields. Follow the field descriptions for values that
364
- replace an entire object, such as `modelParameters`.
365
-
366
- Read credential patches from stdin to keep them out of shell history. JSON is validated before
367
- connecting. The extension validates field names and values before saving. Browser commands accept
368
- `--client NAME|UUID` to select a profile. `automations run` starts an existing automation and
369
- returns its task ID.
370
-
371
- The CLI uses the same browser operations as MCP. Its commands correspond to tasks, data,
372
- images, Skills, settings, and automations. `qz mcp` only returns the connection URL for MCP
373
- clients.
374
-
375
- ## Terminal output
376
-
377
- Interactive terminals show readable text; pipes and redirected output receive JSON. Use `--json`
378
- to request JSON explicitly or `--plain` to keep text when redirecting output. `--no-color` or the
379
- `NO_COLOR` environment variable disables color. `qz mcp` prints only the MCP URL by default;
380
- `qz mcp --json` returns a JSON result.
381
-
382
- In JSON mode, `--wait` and `--stream` emit one final JSON result on stdout. Complete pending-input
383
- notices and submission templates appear on stderr so you can respond while preserving
384
- machine-readable output. MCP snapshots and rejected responses include `input`, with a
385
- `responseTemplate` that binds answers to the current session and wait. Chrome-native permission
386
- requests provide user instructions instead of an approval template.
387
- Exit codes are `0` for success (including reading pending input), `1` for an operation or
388
- task failure or a rejected submission, `2` for invalid arguments, and `130` for Ctrl-C.
389
- Connection errors include the GitHub setup guide and installation link.
390
-
391
- ## Local access
392
-
393
- The service listens on loopback. It validates Host and Origin, rejects redirects, and accepts
394
- extension polling only from extension origins or local clients. Ordinary websites cannot send
395
- requests through the MCP endpoint. Local programs can control connected qz tasks while the
396
- service is running. Run `qz stop` to disconnect.
397
-
398
- Connection metadata and browser registrations are stored in `~/.qz-browser-agent/run/`;
399
- `QZ_STATE_DIR` selects another local directory for isolated tests. Registration writes are atomic;
400
- a failed write leaves the previous registration active. Private pairing proofs stay in local storage
401
- and are omitted from status output. Atomic startup locks prevent duplicate services. Development copies
402
- and published installations use separate identities. The client verifies the service identity,
403
- protocol version, instance, and process before reusing or stopping it. Editing source files or
404
- running a newer package keeps the healthy service and its connections alive. `status` reports
405
- when a different build is available. To load the new service code, finish active work, run
406
- `qz stop`, then `qz connect`.
407
-
408
- ## Package development
409
-
410
- The npm package name is `qz-browser-agent`; the executable name is `qz`. Local development uses
411
- this same package name. The repository root stays private, and this service directory is the
412
- publishable package. Publishing requires separate authorization and ownership of the npm name.
413
-
414
- From the repository root, install the locked dependencies and run the local source:
73
+ **Clients with an `mcpServers` JSON config**, such as Cursor:
415
74
 
416
- ```bash
417
- npm ci
418
- npm run qz -- --version
419
- npm run qz -- connect
420
- npm run qz -- create "Summarize the current page." --stream
421
- ```
422
-
423
- Keep the `--` separator when forwarding options through npm. For a local `qz` executable,
424
- run `npm link` in `services/mcp-bridge`. JavaScript runs directly on Node.js. The published
425
- package contains the runtime files, tool catalog, README, and license.
426
-
427
- ```bash
428
- npm test -- services --match node
429
- node tests/release/npm-package.mjs
75
+ ```json
76
+ {
77
+ "mcpServers": {
78
+ "qz": { "url": "http://127.0.0.1:18765/mcp" }
79
+ }
80
+ }
430
81
  ```
431
82
 
432
- The package check packs the service and installs that tarball in two clean temporary directories
433
- using the public npm registry. It checks the installed command, versions, MCP tools, service reuse,
434
- and shutdown on an isolated port. The test owns its npm configuration, cache, connection state,
435
- and service process. It requires network access to download dependencies.
436
-
437
- Use `--output tests/results/npm/qz-browser-agent-0.1.1.tgz` to retain the verified tarball.
438
- Use `--tarball PATH` to check an existing tarball. The check also runs through
439
- `npm test -- release --match npm-package`.
440
-
441
- ## Publish to npm
442
-
443
- Choose the package version in `services/mcp-bridge/package.json`, complete the repository checks,
444
- and commit the intended source before publishing. CLI and MCP report that same package version.
445
- Each published version identifies immutable package contents; use a new version for updates.
446
-
447
- The **npm package** GitHub Actions workflow tests the CLI and the installed package on Linux,
448
- macOS, and Windows. On a manual run, provide the expected version. With **publish** left unchecked,
449
- it only validates the package and retains the tested tarball. Publishing requires a manual run
450
- from `main` with **publish** checked; all three platforms must pass first.
83
+ CLI and MCP share the same browser connection. The MCP tool list is in the
84
+ [reference](https://github.com/alibaba/qz-browser-agent/blob/main/docs/cli.md#task-and-resource-operations).
451
85
 
452
- Configure the npm package's trusted publisher for the `alibaba/qz-browser-agent` repository,
453
- workflow `npm-package.yml`, and GitHub environment `npm`. Enable direct publishing in that
454
- trusted publisher configuration. The publish job uses OIDC and uploads the exact Linux-tested
455
- tarball. The npm package must be created under an account with publishing rights before this
456
- trusted publisher can be configured. See [npm trusted publishing](https://docs.npmjs.com/trusted-publishers/).
86
+ ## Common commands
457
87
 
458
- For the first manual release, log in with npm, verify the saved tarball, and publish it:
459
-
460
- ```bash
461
- npm login --registry=https://registry.npmjs.org
462
- node tests/release/npm-package.mjs --output tests/results/npm/qz-browser-agent-0.1.1.tgz
463
- npm publish tests/results/npm/qz-browser-agent-0.1.1.tgz --access public --registry=https://registry.npmjs.org
464
- ```
465
-
466
- The root package stays private. Publishing the service does not publish the Chrome extension.
467
- After publication, check `npx qz-browser-agent@0.1.1 --version` from a directory outside the repository.
88
+ | Command | What it does |
89
+ | --- | --- |
90
+ | `qz connect` | Start the local service and pair a browser |
91
+ | `qz status` | Check the connection and service address |
92
+ | `qz browsers` | List paired browsers, or `forget` an offline one |
93
+ | `qz create "PROMPT"` | Start a task; add `--stream` or `--wait` to follow it |
94
+ | `qz send TASK_ID "MESSAGE"` | Send a follow-up, or `--steer` the current run |
95
+ | `qz tasks` | List tasks |
96
+ | `qz show TASK_ID` | Read a task's status, response, or pending question |
97
+ | `qz watch TASK_ID` | Follow a running task until it finishes |
98
+ | `qz submit` / `approve` / `reject` | Answer a question or permission request |
99
+ | `qz cancel TASK_ID` | Stop a task |
100
+ | `qz data` | List, export, or delete data tables |
101
+ | `qz images` | List, export, or delete image collections |
102
+ | `qz skills` | Find, read, or export Skills |
103
+ | `qz settings` | Read or update settings |
104
+ | `qz automations` | List or run automations |
105
+ | `qz stop` | Stop the local service and disconnect all browsers |
106
+
107
+ With several browser profiles connected, choose one with `--client NAME|UUID` (or `-c`).
108
+ Run `qz COMMAND --help` for options. Interactive terminals show readable text; pipes receive JSON.
109
+
110
+ ## Privacy and local access
111
+
112
+ The service accepts connections only on your computer, and ordinary websites cannot use its MCP
113
+ endpoint. Local programs can control connected qz tasks while the service is running. `qz stop`
114
+ disconnects all browsers and MCP clients; tasks already running in the browser keep going.
115
+ Connection settings are stored in `~/.qz-browser-agent/run/`, and pairing credentials never
116
+ leave your computer.
117
+
118
+ ## Reference
119
+
120
+ See the [qz CLI and MCP reference](https://github.com/alibaba/qz-browser-agent/blob/main/docs/cli.md)
121
+ for pairing a specific browser profile, Windows PowerShell notes, updates, task responses,
122
+ exports, output formats, exit codes, and the MCP tool mapping.
123
+
124
+ ## License
125
+
126
+ [Apache-2.0](https://github.com/alibaba/qz-browser-agent/blob/main/LICENSE)
package/package.json CHANGED
@@ -1,9 +1,9 @@
1
1
  {
2
2
  "name": "qz-browser-agent",
3
- "version": "0.1.1",
3
+ "version": "0.1.2",
4
4
  "description": "Local browser tools and MCP access for the qz extension",
5
5
  "type": "module",
6
- "engines": { "node": ">=24" },
6
+ "engines": { "node": ">=22" },
7
7
  "bin": { "qz": "src/bin.mjs" },
8
8
  "files": ["src/*.mjs", "src/catalog.json", "README.md", "LICENSE"],
9
9
  "license": "Apache-2.0",
package/src/bin.mjs CHANGED
@@ -7,19 +7,17 @@ let isEntry = false;
7
7
  try { isEntry = realpathSync(process.argv[1]) === fileURLToPath(import.meta.url); } catch {}
8
8
  if (isEntry) {
9
9
  const argv = process.argv.slice(2);
10
- if (Number(process.versions.node.split(".")[0]) < 24) {
10
+ if (Number(process.versions.node.split(".")[0]) < 22) {
11
11
  const error = {
12
12
  code: "unsupported_node_version",
13
- message: `qz requires Node.js 24 or later. Current version: ${process.versions.node}.`,
14
- hint: "Install Node.js 24 or later, then run qz again.",
13
+ message: `qz requires Node.js 22 or later. Current version: ${process.versions.node}.`,
14
+ hint: "Install Node.js 22 or later, then run qz again.",
15
15
  };
16
16
  if (argv.includes("--json")) process.stdout.write(`${JSON.stringify({ ok: false, error })}\n`);
17
17
  else process.stderr.write(`${error.message}\n${error.hint}\n`);
18
18
  process.exitCode = 1;
19
19
  } else {
20
- const { main } = await import("./cli.mjs");
21
- const controller = new AbortController();
22
- process.once("SIGINT", () => controller.abort());
23
- process.exitCode = await main(argv, { signal: controller.signal });
20
+ const { runMain } = await import("./cli.mjs");
21
+ process.exitCode = await runMain(argv);
24
22
  }
25
23
  }
package/src/cli.mjs CHANGED
@@ -7,7 +7,7 @@ import { ensureDaemon, findDaemon, stopDaemon } from "./daemon.mjs";
7
7
  import { openBrowser } from "./open-browser.mjs";
8
8
  import { parseCommand } from "./args.mjs";
9
9
  import { renderError, renderHelp, renderResult, renderInputNotice, sanitizeTerminalText } from "./terminal.mjs";
10
- import { waitForTask } from "./task-stream.mjs";
10
+ import { TASK_NOT_FOUND_MESSAGE, waitForTask } from "./task-stream.mjs";
11
11
  import { createLiveOutput, outputMode } from "./output.mjs";
12
12
  import { resourceRequest, settingsPatch } from "./cli-resources.mjs";
13
13
  import { PACKAGE_NAME, PACKAGE_VERSION } from "./package-info.mjs";
@@ -73,11 +73,18 @@ function recoveryCommand(command, sessionId, clientId, stream = false) {
73
73
  if (clientId && sanitizeTerminalText(clientId) !== String(clientId)) clientId = "CLIENT_ID";
74
74
  const client = clientId ? ` --client${String(clientId).startsWith("-") ? "=" : " "}${shellArgument(clientId)}` : "";
75
75
  const options = `${client}${stream ? " --stream" : ""}`;
76
+ if (!sessionId) return `qz ${command}${options}`;
76
77
  return String(sessionId).startsWith("-")
77
78
  ? `qz ${command}${options} ${optionTerminator()} ${shellArgument(sessionId)}`
78
79
  : `qz ${command} ${shellArgument(sessionId)}${options}`;
79
80
  }
80
81
 
82
+ function missingTaskDetails(sessionId, clientId) {
83
+ return { sessionId, ...(clientId ? { clientId } : {}),
84
+ hint: "Check the task ID and selected browser. Run qz browsers to inspect browser names and UUIDs. List tasks in the selected browser:",
85
+ command: recoveryCommand("tasks", "", clientId) };
86
+ }
87
+
81
88
  export async function runCli(argv, dependencies = {}) {
82
89
  return executeCommand(parseCommand(argv), dependencies);
83
90
  }
@@ -219,6 +226,7 @@ async function dispatchCommand(parsed, dependencies) {
219
226
  });
220
227
  } catch (error) {
221
228
  const code = error.name === "TimeoutError" ? "timeout" : error.name === "AbortError" ? "interrupted" : error.code || "task_wait_failed";
229
+ if (code === "task_deleted") throw new QzError(code, error.message, { ...error.details, ...missingTaskDetails(sessionId, clientId) });
222
230
  const changed = code === "task_changed";
223
231
  throw new QzError(code, code === "timeout"
224
232
  ? "Stopped watching after the configured --timeout. The browser task may still be running." : error.message,
@@ -283,6 +291,9 @@ async function dispatchCommand(parsed, dependencies) {
283
291
  ...(action === "list" && options.limit !== undefined ? { limit: Number(options.limit) } : {}) };
284
292
  }
285
293
  let result = await call(running.endpoint, name, parameters, requestOptions);
294
+ if (command === "tasks" && action === "get" && result?.session === null) {
295
+ throw new QzError("task_not_found", TASK_NOT_FOUND_MESSAGE, missingTaskDetails(id, clientId));
296
+ }
286
297
  if (command === "tasks" && action === "create" && options.wait) {
287
298
  const sessionId = result?.session?.id || result?.sessionId;
288
299
  if (!sessionId) throw new QzError("invalid_response", "The task was created without an ID. Run qz tasks to find it before retrying.");
@@ -351,10 +362,30 @@ export async function main(argv = process.argv.slice(2), dependencies = {}) {
351
362
  }
352
363
  }
353
364
 
365
+ /** Keep handlers installed while npm forwards duplicate signals and MCP closes. */
366
+ export async function runMain(argv = process.argv.slice(2), dependencies = {}) {
367
+ const controller = new AbortController();
368
+ let interruptedExitCode;
369
+ const interrupt = code => {
370
+ if (controller.signal.aborted) return;
371
+ interruptedExitCode = code;
372
+ controller.abort();
373
+ };
374
+ const onSigint = () => interrupt(130);
375
+ const onSigterm = () => interrupt(143);
376
+ process.on("SIGINT", onSigint);
377
+ process.on("SIGTERM", onSigterm);
378
+ try {
379
+ const code = await main(argv, { ...dependencies, signal: controller.signal });
380
+ return interruptedExitCode ?? code;
381
+ } finally {
382
+ process.removeListener("SIGINT", onSigint);
383
+ process.removeListener("SIGTERM", onSigterm);
384
+ }
385
+ }
386
+
354
387
  let isEntry = false;
355
388
  try { isEntry = realpathSync(process.argv[1]) === fileURLToPath(import.meta.url); } catch {}
356
389
  if (isEntry) {
357
- const controller = new AbortController();
358
- process.once("SIGINT", () => controller.abort());
359
- process.exitCode = await main(process.argv.slice(2), { signal: controller.signal });
390
+ process.exitCode = await runMain();
360
391
  }
package/src/client.mjs CHANGED
@@ -1,5 +1,4 @@
1
1
  import { request } from "node:http";
2
- import { Readable } from "node:stream";
3
2
  import { Client } from "@modelcontextprotocol/sdk/client/index.js";
4
3
  import { StreamableHTTPClientTransport } from "@modelcontextprotocol/sdk/client/streamableHttp.js";
5
4
  import { PACKAGE_VERSION } from "./package-info.mjs";
@@ -27,6 +26,19 @@ export function localUrl(value) {
27
26
  return url;
28
27
  }
29
28
 
29
+ function responseBody(response) {
30
+ const iterator = response[Symbol.asyncIterator]();
31
+ return {
32
+ [Symbol.asyncIterator]() { return this; },
33
+ next: () => iterator.next(),
34
+ return() {
35
+ // An iterator return waits behind a pending read. Destroy the HTTP stream first.
36
+ response.destroy();
37
+ return iterator.return();
38
+ },
39
+ };
40
+ }
41
+
30
42
  // node:http does not inherit proxy environment settings. Every MCP request stays on loopback.
31
43
  export async function localFetch(input, init) {
32
44
  const prepared = new Request(input, init);
@@ -42,7 +54,7 @@ export async function localFetch(input, init) {
42
54
  return;
43
55
  }
44
56
  try {
45
- resolve(new Response([204, 304].includes(res.statusCode) ? null : Readable.toWeb(res), {
57
+ resolve(new Response([204, 304].includes(res.statusCode) ? null : responseBody(res), {
46
58
  status: res.statusCode, headers: new Headers(Object.entries(res.headers)
47
59
  .flatMap(([key, value]) => Array.isArray(value) ? value.map(item => [key, item]) : value === undefined ? [] : [[key, value]])),
48
60
  }));
@@ -5,6 +5,8 @@ const ACTIVE_STATUSES = new Set(["pending", "running", "waiting_user", "paused"]
5
5
  const INPUT_STATUSES = new Set(["waiting_user", "paused"]);
6
6
  const record = value => value && typeof value === "object" && !Array.isArray(value) ? value : {};
7
7
 
8
+ export const TASK_NOT_FOUND_MESSAGE = "The task was not found in the selected browser. It may have been deleted, the task ID may be incorrect, or a different browser may be selected.";
9
+
8
10
  function taskStatus(snapshot) {
9
11
  const status = String(snapshot.status || snapshot.runtime?.status || snapshot.state?.status || "").trim();
10
12
  if (status === "waitingUser") return "waiting_user";
@@ -55,8 +57,8 @@ export async function waitForTask({ sessionId, clientId, timeoutSeconds = null,
55
57
  if (deadline !== null && Date.now() >= deadline) controller.abort(timeout);
56
58
  activeSignal.throwIfAborted();
57
59
  };
58
- const pollingDelay = () => delay(deadline === null ? pollIntervalMs : Math.min(pollIntervalMs, Math.max(0, deadline - Date.now())),
59
- undefined, { signal: activeSignal });
60
+ // The total deadline cancels this sleep; shortening it can wake before that deadline.
61
+ const pollingDelay = () => delay(pollIntervalMs, undefined, { signal: activeSignal });
60
62
  const readSnapshot = async () => {
61
63
  checkActive();
62
64
  const milliseconds = Math.max(1, Math.ceil(requestTimeoutSeconds * 1000));
@@ -122,7 +124,7 @@ export async function waitForTask({ sessionId, clientId, timeoutSeconds = null,
122
124
  throw Object.assign(new Error("The task snapshot belongs to a different session."), { code: "task_changed" });
123
125
  }
124
126
  if (Object.hasOwn(snapshot, "session") && snapshot.session === null) {
125
- throw Object.assign(new Error("The task was deleted while waiting for its result."), { code: "task_deleted" });
127
+ throw Object.assign(new Error(TASK_NOT_FOUND_MESSAGE), { code: "task_deleted" });
126
128
  }
127
129
  const runtime = record(snapshot.runtime);
128
130
  const canonicalInput = Object.hasOwn(snapshot, "input") ? record(snapshot.input) : null;
package/src/terminal.mjs CHANGED
@@ -7,7 +7,9 @@ const palette = { accent: 36, muted: 90, error: 31, waiting: 33 };
7
7
 
8
8
  // Remote pages and model responses are text, never terminal instructions.
9
9
  export function sanitizeTerminalText(value) {
10
- return stripVTControlCharacters(String(value ?? ""))
10
+ // Early Node 22 versions do not strip OSC strings terminated by ESC + backslash.
11
+ const text = String(value ?? "").replace(/(?:\u001b\]|\u009d)[\s\S]*?(?:\u0007|\u001b\\|\u009c|$)/g, "");
12
+ return stripVTControlCharacters(text)
11
13
  .replace(/\r\n?/g, "\n")
12
14
  .replace(/[\u0000-\u0008\u000b-\u001f\u007f-\u009f]/g, "")
13
15
  .replace(/[\u061c\u200e\u200f\u202a-\u202e\u2066-\u2069]/g, "")
package/src/tools.mjs CHANGED
@@ -91,8 +91,10 @@ async function executeBrowserTool(state, name, args, { signal, connectionSignal,
91
91
  : cause.name === "TimeoutError" ? "timeout" : cause.name === "AbortError" ? "interrupted" : "task_wait_failed";
92
92
  const error = Object.assign(new Error(cause.message, { cause }), { code });
93
93
  error.details = { ...cause.details, sessionId, clientId: args.clientId,
94
- recovery: { tool: code === "task_changed" ? "qingzhou_get_session_snapshot" : "qingzhou_watch_task",
95
- arguments: { sessionId, clientId: args.clientId } } };
94
+ recovery: code === "task_deleted"
95
+ ? { tool: "qingzhou_list_sessions", arguments: { clientId: args.clientId } }
96
+ : { tool: code === "task_changed" ? "qingzhou_get_session_snapshot" : "qingzhou_watch_task",
97
+ arguments: { sessionId, clientId: args.clientId } } };
96
98
  throw error;
97
99
  }
98
100
  };